@mastra/factory 0.17.3-alpha.5 → 0.18.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/dist/auth.d.ts.map +1 -1
  2. package/dist/auth.js +15 -4
  3. package/dist/auth.js.map +1 -1
  4. package/dist/boards/review.d.ts +2 -0
  5. package/dist/boards/review.d.ts.map +1 -1
  6. package/dist/boards/review.js +16 -6
  7. package/dist/boards/review.js.map +1 -1
  8. package/dist/boards/transition-policy.d.ts +3 -3
  9. package/dist/boards/transition-policy.d.ts.map +1 -1
  10. package/dist/boards/transition-policy.js.map +1 -1
  11. package/dist/boards/work-transition-policy.d.ts.map +1 -1
  12. package/dist/boards/work-transition-policy.js +13 -3
  13. package/dist/boards/work-transition-policy.js.map +1 -1
  14. package/dist/capabilities/intake.d.ts +2 -0
  15. package/dist/capabilities/intake.d.ts.map +1 -1
  16. package/dist/factory.d.ts.map +1 -1
  17. package/dist/factory.js +14 -3
  18. package/dist/factory.js.map +1 -1
  19. package/dist/integrations/github/default-rules.d.ts +17 -1
  20. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  21. package/dist/integrations/github/default-rules.js +30 -6
  22. package/dist/integrations/github/default-rules.js.map +1 -1
  23. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  24. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  25. package/dist/integrations/github/routes.d.ts.map +1 -1
  26. package/dist/integrations/github/routes.js +1 -0
  27. package/dist/integrations/github/routes.js.map +1 -1
  28. package/dist/integrations/github/rules.d.ts.map +1 -1
  29. package/dist/integrations/github/rules.js +48 -2
  30. package/dist/integrations/github/rules.js.map +1 -1
  31. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  32. package/dist/integrations/github/sandbox.js.map +1 -1
  33. package/dist/integrations/gitlab/api.d.ts.map +1 -1
  34. package/dist/integrations/gitlab/api.js.map +1 -1
  35. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  36. package/dist/integrations/gitlab/default-rules.js +1 -0
  37. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  38. package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
  39. package/dist/integrations/gitlab/reconciler.js.map +1 -1
  40. package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
  41. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  42. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  43. package/dist/integrations/gitlab/routes.js +1 -0
  44. package/dist/integrations/gitlab/routes.js.map +1 -1
  45. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  46. package/dist/integrations/gitlab/rules.js +66 -0
  47. package/dist/integrations/gitlab/rules.js.map +1 -1
  48. package/dist/integrations/gitlab/version-control.d.ts.map +1 -1
  49. package/dist/integrations/gitlab/version-control.js.map +1 -1
  50. package/dist/integrations/incidentio/api.d.ts.map +1 -1
  51. package/dist/integrations/incidentio/api.js.map +1 -1
  52. package/dist/integrations/incidentio/intake.d.ts.map +1 -1
  53. package/dist/integrations/incidentio/intake.js.map +1 -1
  54. package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
  55. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  56. package/dist/integrations/linear/default-rules.d.ts +2 -1
  57. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  58. package/dist/integrations/linear/default-rules.js +1 -0
  59. package/dist/integrations/linear/default-rules.js.map +1 -1
  60. package/dist/integrations/linear/integration.d.ts.map +1 -1
  61. package/dist/integrations/linear/integration.js +2 -0
  62. package/dist/integrations/linear/integration.js.map +1 -1
  63. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  64. package/dist/integrations/linear/issue-reconciler.js +3 -0
  65. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  66. package/dist/integrations/linear/routes.d.ts.map +1 -1
  67. package/dist/integrations/linear/routes.js +2 -1
  68. package/dist/integrations/linear/routes.js.map +1 -1
  69. package/dist/integrations/linear/rules.d.ts +1 -0
  70. package/dist/integrations/linear/rules.d.ts.map +1 -1
  71. package/dist/integrations/linear/rules.js.map +1 -1
  72. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  73. package/dist/integrations/slack/emoji-shortcodes.generated.js.map +1 -1
  74. package/dist/integrations/slack/feed-publisher.d.ts.map +1 -1
  75. package/dist/integrations/slack/feed-publisher.js.map +1 -1
  76. package/dist/integrations/slack/slack.d.ts +7 -7
  77. package/dist/integrations/slack/slack.d.ts.map +1 -1
  78. package/dist/integrations/slack/slack.js +157 -23
  79. package/dist/integrations/slack/slack.js.map +1 -1
  80. package/dist/integrations/subscription-session.d.ts +3 -1
  81. package/dist/integrations/subscription-session.d.ts.map +1 -1
  82. package/dist/integrations/subscription-session.js +4 -2
  83. package/dist/integrations/subscription-session.js.map +1 -1
  84. package/dist/platform-auth-host.d.ts +4 -0
  85. package/dist/platform-auth-host.d.ts.map +1 -0
  86. package/dist/platform-auth-host.js +18 -0
  87. package/dist/platform-auth-host.js.map +1 -0
  88. package/dist/routes/contracts.d.ts +23 -0
  89. package/dist/routes/contracts.d.ts.map +1 -1
  90. package/dist/routes/contracts.js +21 -0
  91. package/dist/routes/contracts.js.map +1 -1
  92. package/dist/routes/intake.d.ts.map +1 -1
  93. package/dist/routes/intake.js +15 -1
  94. package/dist/routes/intake.js.map +1 -1
  95. package/dist/routes/projects.d.ts +22 -2
  96. package/dist/routes/projects.d.ts.map +1 -1
  97. package/dist/routes/projects.js +101 -0
  98. package/dist/routes/projects.js.map +1 -1
  99. package/dist/routes/surface.d.ts +1 -1
  100. package/dist/routes/surface.d.ts.map +1 -1
  101. package/dist/routes/surface.js +47 -6
  102. package/dist/routes/surface.js.map +1 -1
  103. package/dist/routes/work-items.d.ts.map +1 -1
  104. package/dist/routes/work-items.js +6 -1
  105. package/dist/routes/work-items.js.map +1 -1
  106. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  107. package/dist/rules/dispatch-errors.js +4 -0
  108. package/dist/rules/dispatch-errors.js.map +1 -1
  109. package/dist/rules/dispatcher.d.ts.map +1 -1
  110. package/dist/rules/dispatcher.js +14 -6
  111. package/dist/rules/dispatcher.js.map +1 -1
  112. package/dist/rules/processor.d.ts.map +1 -1
  113. package/dist/rules/processor.js +9 -1
  114. package/dist/rules/processor.js.map +1 -1
  115. package/dist/rules/review-source-tool.d.ts +103 -0
  116. package/dist/rules/review-source-tool.d.ts.map +1 -0
  117. package/dist/rules/review-source-tool.js +109 -0
  118. package/dist/rules/review-source-tool.js.map +1 -0
  119. package/dist/rules/start-coordinator.d.ts +7 -1
  120. package/dist/rules/start-coordinator.d.ts.map +1 -1
  121. package/dist/rules/start-coordinator.js +56 -2
  122. package/dist/rules/start-coordinator.js.map +1 -1
  123. package/dist/rules/tools.d.ts +1 -0
  124. package/dist/rules/tools.d.ts.map +1 -1
  125. package/dist/rules/tools.js +107 -32
  126. package/dist/rules/tools.js.map +1 -1
  127. package/dist/rules/transition-service.d.ts +4 -4
  128. package/dist/rules/transition-service.d.ts.map +1 -1
  129. package/dist/rules/transition-service.js +3 -2
  130. package/dist/rules/transition-service.js.map +1 -1
  131. package/dist/rules/types.d.ts +2 -0
  132. package/dist/rules/types.d.ts.map +1 -1
  133. package/dist/rules/types.js.map +1 -1
  134. package/dist/sandbox/materialization.d.ts +5 -1
  135. package/dist/sandbox/materialization.d.ts.map +1 -1
  136. package/dist/sandbox/materialization.js.map +1 -1
  137. package/dist/sandbox/session-sandbox.d.ts +13 -1
  138. package/dist/sandbox/session-sandbox.d.ts.map +1 -1
  139. package/dist/sandbox/session-sandbox.js.map +1 -1
  140. package/dist/session/factory-session.d.ts +14 -4
  141. package/dist/session/factory-session.d.ts.map +1 -1
  142. package/dist/session/factory-session.js +32 -11
  143. package/dist/session/factory-session.js.map +1 -1
  144. package/dist/session/work-item-repository.d.ts +21 -0
  145. package/dist/session/work-item-repository.d.ts.map +1 -0
  146. package/dist/session/work-item-repository.js +91 -0
  147. package/dist/session/work-item-repository.js.map +1 -0
  148. package/dist/skills/service.d.ts.map +1 -1
  149. package/dist/skills/service.js +16 -6
  150. package/dist/skills/service.js.map +1 -1
  151. package/dist/storage/domains/intake/base.d.ts +1 -0
  152. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  153. package/dist/storage/domains/intake/base.js.map +1 -1
  154. package/dist/storage/domains/integrations/base.d.ts.map +1 -1
  155. package/dist/storage/domains/integrations/base.js.map +1 -1
  156. package/dist/storage/domains/work-items/base.d.ts +15 -2
  157. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  158. package/dist/storage/domains/work-items/base.js +31 -1
  159. package/dist/storage/domains/work-items/base.js.map +1 -1
  160. package/dist/supervisor/session-messaging.d.ts +4 -1
  161. package/dist/supervisor/session-messaging.d.ts.map +1 -1
  162. package/dist/supervisor/session-messaging.js +8 -2
  163. package/dist/supervisor/session-messaging.js.map +1 -1
  164. package/dist/supervisor/write-tools.d.ts +2 -1
  165. package/dist/supervisor/write-tools.d.ts.map +1 -1
  166. package/dist/supervisor/write-tools.js +9 -2
  167. package/dist/supervisor/write-tools.js.map +1 -1
  168. package/dist/workspace.d.ts +7 -1
  169. package/dist/workspace.d.ts.map +1 -1
  170. package/dist/workspace.js +53 -14
  171. package/dist/workspace.js.map +1 -1
  172. package/factory-skills/factory-complete-issue/SKILL.md +4 -2
  173. package/factory-skills/factory-gitlab-rereview/SKILL.md +3 -2
  174. package/factory-skills/factory-gitlab-review/SKILL.md +19 -3
  175. package/factory-skills/factory-plan/SKILL.md +11 -0
  176. package/factory-skills/factory-rereview/SKILL.md +37 -12
  177. package/factory-skills/factory-review/SKILL.md +37 -12
  178. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/linear/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Linear intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the WorkOS auth gate.\n * Mirrors the GitHub module: every route re-resolves the authenticated user\n * from the request cookie and scopes all rows by the caller's WorkOS org, so an\n * org can only ever see its own Linear connection and issues.\n *\n * When the feature is disabled (`isLinearFeatureEnabled()` false),\n * `buildLinearRoutes` returns only `GET /web/linear/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Linear UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { isTerminalWorkItem } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport { isTerminalFactoryRuleStage } from '../../rules/types.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport { linearClaimKey } from './claim.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\nimport type { LinearRulesIngress } 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;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\n/**\n * Non-secret diagnostic snapshot of every Linear feature gate, mirroring the\n * GitHub diagnostics shape. Only booleans — never values.\n */\nexport interface LinearFeatureDiagnostics {\n linearAppConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountLinearRoutesOptions {\n /**\n * The integration instance providing OAuth + GraphQL access. Required for\n * everything beyond the disabled `status` route.\n */\n linear?: LinearIntegration;\n /** Host auth seam. Linear connections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Absolute base URL of the web server (e.g. `http://localhost:4111`), used to\n * build the OAuth redirect URI when one isn't explicitly configured.\n */\n baseUrl?: string;\n /** Explicit OAuth callback URI; defaults to `<baseUrl>/auth/linear/callback`. */\n redirectUri?: string;\n /**\n * Shared OAuth `state` signer (created once per boot by the factory).\n * Required for the connect/callback flow; when absent, only the disabled\n * `status` route is served.\n */\n stateSigner?: StateSigner;\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 project domain, used to keep single-project installs working\n * without any source binding. When absent, unbound sources are treated as\n * belonging to no project.\n */\n projects?: { list(input: { orgId: string }): Promise<unknown[]> };\n ingestFactoryIssues?: (input: LinearRulesIngress) => Promise<unknown>;\n /**\n * Work-item lookup so the detail route can keep serving a card this Factory\n * already holds after the issue's winning source was routed elsewhere. When\n * absent, details resolve only through sources routed to the Factory.\n */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource' | 'getByClaimKey'>;\n /** Installed boards, so a held card's terminal status follows its own board. */\n boards?: BoardRegistry;\n}\n\n/**\n * Narrow the caller's selected Linear sources to the ones that feed this\n * Factory project.\n *\n * A Linear issue carries no Factory project of its own, so without a binding\n * every board view would ingest every selected source's issues into whichever\n * project happened to be on screen. Routing is explicit: a source feeds this\n * project only when its binding names both the project and a board. Returns\n * the bound board per source so the ingest lands cards where the user asked.\n */\nasync function scopeSourceIdsToProject({\n intake,\n orgId,\n factoryProjectId,\n selectedIds,\n}: {\n intake: IntakeStorage;\n orgId: string;\n factoryProjectId: string;\n selectedIds: string[];\n}): Promise<Record<string, string>> {\n const selected = new Set(selectedIds);\n const intakeBoards: Record<string, string> = {};\n for (const binding of await intake.listBindings({ orgId, integrationId: 'linear' })) {\n if (binding.factoryProjectId === factoryProjectId && binding.board && selected.has(binding.sourceId)) {\n intakeBoards[binding.sourceId] = binding.board;\n }\n }\n return intakeBoards;\n}\n\n/**\n * Resolve the org-scoped tenant for a Linear request. The connection is\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the GitHub 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: 'Linear intake requires an organization. Personal accounts cannot connect Linear.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Linear pagination cursor from the query string. Cursors\n * are server-issued (`pageInfo.endCursor`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Linear.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 8192 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Human issue key as it appears on a card (`ENG-123`). */\nconst ISSUE_IDENTIFIER_RE = /^[A-Za-z][A-Za-z0-9]{0,9}-\\d{1,7}$/;\n/** Project sources are more specific than their team and win every routed read. */\nfunction winningLinearSourceId(\n linear: LinearIntegration,\n sourceIds: string[],\n issue: Parameters<LinearIntegration['sourceMatchesIssue']>[1],\n): string | null {\n const matching = sourceIds.filter(sourceId => linear.sourceMatchesIssue(sourceId, issue));\n return matching.find(sourceId => !sourceId.startsWith('linear-team:')) ?? matching[0] ?? null;\n}\n\n/**\n * The card this Factory holds for an issue, if any: by the stable issue id when\n * the SPA sent one, else by the identifier the card was filed under.\n */\nasync function findHeldCard(\n options: MountLinearRoutesOptions,\n orgId: string,\n factoryProjectId: string,\n identifier: string,\n issueId: string | undefined,\n) {\n if (!options.workItems) return null;\n if (issueId) {\n const claimant = await options.workItems.getByClaimKey({ orgId, claimKey: linearClaimKey(issueId) });\n if (claimant) return claimant.factoryProjectId === factoryProjectId ? claimant : null;\n }\n return options.workItems.getByProjectSource({\n orgId,\n factoryProjectId,\n source: { integrationId: 'linear', type: 'issue', externalId: `linear:${identifier}` },\n });\n}\n\n/** Map a Linear read failure to the API response for the SPA. */\nfunction linearFetchError(c: RouteContext, err: unknown) {\n if ((err as { code?: unknown }).code === 'invalid_cursor') {\n return c.json({ error: 'invalid_cursor' }, 400);\n }\n if (err instanceof LinearReauthRequiredError || (err as { status?: number }).status === 401) {\n return c.json({ error: 'linear_reauth_required', message: new LinearReauthRequiredError().message }, 409);\n }\n return c.json({ error: 'linear_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Linear 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 buildLinearRoutes(options: MountLinearRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { linear, auth, stateSigner, intake } = options;\n const enabled = Boolean(linear) && auth.enabled();\n const diagnostics = (): LinearFeatureDiagnostics => ({\n linearAppConfigured: Boolean(linear),\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/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !linear || !stateSigner) {\n return c.json({\n enabled: false,\n connected: false,\n workspace: 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 if (!tenant.orgId) {\n return c.json({\n enabled: true,\n organizationRequired: true,\n connected: false,\n workspace: null,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n const connection = await linear.loadConnection(tenant.orgId);\n return c.json({\n enabled: true,\n connected: Boolean(connection),\n workspace: connection ? { name: connection.workspaceName, urlKey: connection.workspaceUrlKey } : null,\n reason: connection ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n },\n }),\n );\n\n // Without the integration instance or a state signer the connect/callback\n // flow cannot talk to Linear or bind the OAuth round-trip to a tenant —\n // serve only the disabled `status` route (mirrors the feature gate).\n if (!enabled || !linear || !stateSigner || !intake) {\n return routes;\n }\n\n const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? '').replace(/\\/$/, '')}/auth/linear/callback`;\n\n // ── Connect: send the user to Linear's OAuth consent screen ─────────────\n routes.push(\n registerApiRoute('/auth/linear/connect', {\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 const state = stateSigner.sign(resolved.tenant.orgId, resolved.tenant.userId);\n return c.redirect(linear.buildAuthorizeUrl(state, redirectUri));\n },\n }),\n );\n\n // ── Callback: exchange the code, persist the connection for the org ─────\n routes.push(\n registerApiRoute('/auth/linear/callback', {\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 const { orgId, userId } = resolved.tenant;\n\n // CSRF / cross-tenant linking protection: the signed state must belong\n // to the same logged-in user *and* their current org.\n const stateTenant = stateSigner.verify(c.req.query('state'));\n if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {\n console.warn('[Linear] OAuth callback rejected: state/tenant mismatch.');\n return c.redirect('/?linear=error');\n }\n\n const code = c.req.query('code');\n if (!code) {\n // User denied consent (or Linear returned an error).\n return c.redirect('/?linear=error');\n }\n\n try {\n const tokens = await linear.exchangeOAuthCode(code, redirectUri);\n const workspace = await linear.fetchWorkspace(tokens.accessToken);\n await linear.upsertConnection({\n orgId,\n userId,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n workspaceName: workspace.name,\n workspaceUrlKey: workspace.urlKey,\n });\n } catch (error) {\n console.warn(`[Linear] OAuth callback failed to persist connection for org ${orgId}.`, error);\n return c.redirect('/?linear=error');\n }\n\n return c.redirect('/?linear=connected');\n },\n }),\n );\n\n // ── List the workspace's projects (Settings intake-source picker) ───────\n routes.push(\n registerApiRoute('/web/linear/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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear projects.' }, 409);\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const projects = await linear.listProjects(accessToken);\n return c.json({ projects });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's teams (Settings intake-source picker) ──────────\n routes.push(\n registerApiRoute('/web/linear/teams', {\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 connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear teams.' }, 409);\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const teams = await linear.listTeams(accessToken);\n return c.json({ teams });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's active issues (cursor-paged) ───────────────────\n // Respects the org's intake config: disabled Linear intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/linear/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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['linear'] });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n\n // No sources selected means nothing is synced — don't fan out to Linear.\n const selectedIds = selection.sourceIds ?? [];\n // A board request is also an ingest, so it only ever sees the sources\n // routed to a board of that Factory project. Sources may be projects or\n // whole teams; both are keyed by their opaque source id.\n const intakeBoards = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const routedSourceIds = intakeBoards ? Object.keys(intakeBoards) : selectedIds;\n if (routedSourceIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const { issues, nextCursor } = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds: routedSourceIds,\n attributionSourceIds: selectedIds,\n cursor: after,\n });\n // Source precedence must be resolved against the complete selection,\n // then the winning issues can be narrowed to this Factory project.\n const routedIssues = intakeBoards\n ? issues.filter(issue => issue.sourceId != null && routedSourceIds.includes(issue.sourceId))\n : issues;\n const issuePayload = routedIssues.map(issue => ({\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,\n creator: issue.author,\n team: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId ?? null,\n }));\n if (factoryProjectId && intakeBoards && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n intakeBoards,\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/linear/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 if (!ISSUE_IDENTIFIER_RE.test(identifier)) return c.json({ error: 'invalid_identifier' }, 400);\n const issueId = c.req.query('issueId');\n if (issueId !== undefined && (issueId.length === 0 || issueId.length > 512)) {\n return c.json({ error: 'invalid_issue_id' }, 400);\n }\n const issueReference = issueId ?? identifier;\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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['linear'] });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n const selectedIds = selection.sourceIds ?? [];\n const routedSourceIds = Object.keys(\n await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n }),\n );\n // A card this Factory already ingested stays readable after its issue's\n // winning source moved to a source routed elsewhere: the fetch widens to\n // every selected source (never beyond the selection), and the routing\n // check is waived for that card alone. Without a live card, the strict\n // routed-source rule applies.\n const held = await findHeldCard(options, resolved.tenant.orgId, factoryProjectId, identifier, issueId);\n const holdsLiveCard =\n held != null &&\n !(options.boards ? isTerminalWorkItem(options.boards, held) : isTerminalFactoryRuleStage(held.stages));\n if (routedSourceIds.length === 0 && !holdsLiveCard) return c.json({ error: 'issue_not_found' }, 404);\n const fetchSourceIds = holdsLiveCard ? selectedIds : routedSourceIds;\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const issue = await linear.fetchIssueDetail(accessToken, issueReference, selectedIds, fetchSourceIds);\n const matchesReference = issueId !== undefined ? issue?.id === issueId : issue?.identifier === identifier;\n const winningSourceId = issue ? winningLinearSourceId(linear, selectedIds, issue) : null;\n const isRouted = winningSourceId != null && (holdsLiveCard || routedSourceIds.includes(winningSourceId));\n // Reads exactly like an issue that doesn't exist.\n if (!issue || !matchesReference || !isRouted) {\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 linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;;;;AA+BA,MAAM,UAAU;;AAGhB,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;;;;;;;;;;;AAiEA,eAAe,wBAAwB,EACrC,QACA,OACA,kBACA,eAMkC;CAClC,MAAM,WAAW,IAAI,IAAI,WAAW;CACpC,MAAM,eAAuC,CAAC;CAC9C,KAAK,MAAM,WAAW,MAAM,OAAO,aAAa;EAAE;EAAO,eAAe;CAAS,CAAC,GAChF,IAAI,QAAQ,qBAAqB,oBAAoB,QAAQ,SAAS,SAAS,IAAI,QAAQ,QAAQ,GACjG,aAAa,QAAQ,YAAY,QAAQ;CAG7C,OAAO;AACT;;;;;;AAOA,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,I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AAC,GAAG,GAAG;GACvC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/linear/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Linear intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the WorkOS auth gate.\n * Mirrors the GitHub module: every route re-resolves the authenticated user\n * from the request cookie and scopes all rows by the caller's WorkOS org, so an\n * org can only ever see its own Linear connection and issues.\n *\n * When the feature is disabled (`isLinearFeatureEnabled()` false),\n * `buildLinearRoutes` returns only `GET /web/linear/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Linear UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { isTerminalWorkItem } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport { isTerminalFactoryRuleStage } from '../../rules/types.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport { linearClaimKey } from './claim.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\nimport type { LinearRulesIngress } 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;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\n/**\n * Non-secret diagnostic snapshot of every Linear feature gate, mirroring the\n * GitHub diagnostics shape. Only booleans — never values.\n */\nexport interface LinearFeatureDiagnostics {\n linearAppConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountLinearRoutesOptions {\n /**\n * The integration instance providing OAuth + GraphQL access. Required for\n * everything beyond the disabled `status` route.\n */\n linear?: LinearIntegration;\n /** Host auth seam. Linear connections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Absolute base URL of the web server (e.g. `http://localhost:4111`), used to\n * build the OAuth redirect URI when one isn't explicitly configured.\n */\n baseUrl?: string;\n /** Explicit OAuth callback URI; defaults to `<baseUrl>/auth/linear/callback`. */\n redirectUri?: string;\n /**\n * Shared OAuth `state` signer (created once per boot by the factory).\n * Required for the connect/callback flow; when absent, only the disabled\n * `status` route is served.\n */\n stateSigner?: StateSigner;\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 project domain, used to keep single-project installs working\n * without any source binding. When absent, unbound sources are treated as\n * belonging to no project.\n */\n projects?: { list(input: { orgId: string }): Promise<unknown[]> };\n ingestFactoryIssues?: (input: LinearRulesIngress) => Promise<unknown>;\n /**\n * Work-item lookup so the detail route can keep serving a card this Factory\n * already holds after the issue's winning source was routed elsewhere. When\n * absent, details resolve only through sources routed to the Factory.\n */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource' | 'getByClaimKey'>;\n /** Installed boards, so a held card's terminal status follows its own board. */\n boards?: BoardRegistry;\n}\n\n/**\n * Narrow the caller's selected Linear sources to the ones that feed this\n * Factory project.\n *\n * A Linear issue carries no Factory project of its own, so without a binding\n * every board view would ingest every selected source's issues into whichever\n * project happened to be on screen. Routing is explicit: a source feeds this\n * project only when its binding names both the project and a board. Returns\n * the bound board per source so the ingest lands cards where the user asked.\n */\nasync function scopeSourceIdsToProject({\n intake,\n orgId,\n factoryProjectId,\n selectedIds,\n}: {\n intake: IntakeStorage;\n orgId: string;\n factoryProjectId: string;\n selectedIds: string[];\n}): Promise<Record<string, string>> {\n const selected = new Set(selectedIds);\n const intakeBoards: Record<string, string> = {};\n for (const binding of await intake.listBindings({ orgId, integrationId: 'linear' })) {\n if (binding.factoryProjectId === factoryProjectId && binding.board && selected.has(binding.sourceId)) {\n intakeBoards[binding.sourceId] = binding.board;\n }\n }\n return intakeBoards;\n}\n\n/**\n * Resolve the org-scoped tenant for a Linear request. The connection is\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the GitHub 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: 'Linear intake requires an organization. Personal accounts cannot connect Linear.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Linear pagination cursor from the query string. Cursors\n * are server-issued (`pageInfo.endCursor`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Linear.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 8192 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Human issue key as it appears on a card (`ENG-123`). */\nconst ISSUE_IDENTIFIER_RE = /^[A-Za-z][A-Za-z0-9]{0,9}-\\d{1,7}$/;\n/** Project sources are more specific than their team and win every routed read. */\nfunction winningLinearSourceId(\n linear: LinearIntegration,\n sourceIds: string[],\n issue: Parameters<LinearIntegration['sourceMatchesIssue']>[1],\n): string | null {\n const matching = sourceIds.filter(sourceId => linear.sourceMatchesIssue(sourceId, issue));\n return matching.find(sourceId => !sourceId.startsWith('linear-team:')) ?? matching[0] ?? null;\n}\n\n/**\n * The card this Factory holds for an issue, if any: by the stable issue id when\n * the SPA sent one, else by the identifier the card was filed under.\n */\nasync function findHeldCard(\n options: MountLinearRoutesOptions,\n orgId: string,\n factoryProjectId: string,\n identifier: string,\n issueId: string | undefined,\n) {\n if (!options.workItems) return null;\n if (issueId) {\n const claimant = await options.workItems.getByClaimKey({ orgId, claimKey: linearClaimKey(issueId) });\n if (claimant) return claimant.factoryProjectId === factoryProjectId ? claimant : null;\n }\n return options.workItems.getByProjectSource({\n orgId,\n factoryProjectId,\n source: { integrationId: 'linear', type: 'issue', externalId: `linear:${identifier}` },\n });\n}\n\n/** Map a Linear read failure to the API response for the SPA. */\nfunction linearFetchError(c: RouteContext, err: unknown) {\n if ((err as { code?: unknown }).code === 'invalid_cursor') {\n return c.json({ error: 'invalid_cursor' }, 400);\n }\n if (err instanceof LinearReauthRequiredError || (err as { status?: number }).status === 401) {\n return c.json({ error: 'linear_reauth_required', message: new LinearReauthRequiredError().message }, 409);\n }\n return c.json({ error: 'linear_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Linear 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 buildLinearRoutes(options: MountLinearRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { linear, auth, stateSigner, intake } = options;\n const enabled = Boolean(linear) && auth.enabled();\n const diagnostics = (): LinearFeatureDiagnostics => ({\n linearAppConfigured: Boolean(linear),\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/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !linear || !stateSigner) {\n return c.json({\n enabled: false,\n connected: false,\n workspace: 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 if (!tenant.orgId) {\n return c.json({\n enabled: true,\n organizationRequired: true,\n connected: false,\n workspace: null,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n const connection = await linear.loadConnection(tenant.orgId);\n return c.json({\n enabled: true,\n connected: Boolean(connection),\n workspace: connection ? { name: connection.workspaceName, urlKey: connection.workspaceUrlKey } : null,\n reason: connection ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n },\n }),\n );\n\n // Without the integration instance or a state signer the connect/callback\n // flow cannot talk to Linear or bind the OAuth round-trip to a tenant —\n // serve only the disabled `status` route (mirrors the feature gate).\n if (!enabled || !linear || !stateSigner || !intake) {\n return routes;\n }\n\n const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? '').replace(/\\/$/, '')}/auth/linear/callback`;\n\n // ── Connect: send the user to Linear's OAuth consent screen ─────────────\n routes.push(\n registerApiRoute('/auth/linear/connect', {\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 const state = stateSigner.sign(resolved.tenant.orgId, resolved.tenant.userId);\n return c.redirect(linear.buildAuthorizeUrl(state, redirectUri));\n },\n }),\n );\n\n // ── Callback: exchange the code, persist the connection for the org ─────\n routes.push(\n registerApiRoute('/auth/linear/callback', {\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 const { orgId, userId } = resolved.tenant;\n\n // CSRF / cross-tenant linking protection: the signed state must belong\n // to the same logged-in user *and* their current org.\n const stateTenant = stateSigner.verify(c.req.query('state'));\n if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {\n console.warn('[Linear] OAuth callback rejected: state/tenant mismatch.');\n return c.redirect('/?linear=error');\n }\n\n const code = c.req.query('code');\n if (!code) {\n // User denied consent (or Linear returned an error).\n return c.redirect('/?linear=error');\n }\n\n try {\n const tokens = await linear.exchangeOAuthCode(code, redirectUri);\n const workspace = await linear.fetchWorkspace(tokens.accessToken);\n await linear.upsertConnection({\n orgId,\n userId,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n workspaceName: workspace.name,\n workspaceUrlKey: workspace.urlKey,\n });\n } catch (error) {\n console.warn(`[Linear] OAuth callback failed to persist connection for org ${orgId}.`, error);\n return c.redirect('/?linear=error');\n }\n\n return c.redirect('/?linear=connected');\n },\n }),\n );\n\n // ── List the workspace's projects (Settings intake-source picker) ───────\n routes.push(\n registerApiRoute('/web/linear/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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear projects.' }, 409);\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const projects = await linear.listProjects(accessToken);\n return c.json({ projects });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's teams (Settings intake-source picker) ──────────\n routes.push(\n registerApiRoute('/web/linear/teams', {\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 connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear teams.' }, 409);\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const teams = await linear.listTeams(accessToken);\n return c.json({ teams });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's active issues (cursor-paged) ───────────────────\n // Respects the org's intake config: disabled Linear intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/linear/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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['linear'] });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n\n // No sources selected means nothing is synced — don't fan out to Linear.\n const selectedIds = selection.sourceIds ?? [];\n // A board request is also an ingest, so it only ever sees the sources\n // routed to a board of that Factory project. Sources may be projects or\n // whole teams; both are keyed by their opaque source id.\n const intakeBoards = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const routedSourceIds = intakeBoards ? Object.keys(intakeBoards) : selectedIds;\n if (routedSourceIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const { issues, nextCursor } = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds: routedSourceIds,\n attributionSourceIds: selectedIds,\n cursor: after,\n });\n // Source precedence must be resolved against the complete selection,\n // then the winning issues can be narrowed to this Factory project.\n const routedIssues = intakeBoards\n ? issues.filter(issue => issue.sourceId != null && routedSourceIds.includes(issue.sourceId))\n : issues;\n const issuePayload = routedIssues.map(issue => ({\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,\n creator: issue.author,\n team: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId ?? null,\n projectId: issue.projectId ?? null,\n }));\n if (factoryProjectId && intakeBoards && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n intakeBoards,\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/linear/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 if (!ISSUE_IDENTIFIER_RE.test(identifier)) return c.json({ error: 'invalid_identifier' }, 400);\n const issueId = c.req.query('issueId');\n if (issueId !== undefined && (issueId.length === 0 || issueId.length > 512)) {\n return c.json({ error: 'invalid_issue_id' }, 400);\n }\n const issueReference = issueId ?? identifier;\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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['linear'] });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n const selectedIds = selection.sourceIds ?? [];\n const routedSourceIds = Object.keys(\n await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n }),\n );\n // A card this Factory already ingested stays readable after its issue's\n // winning source moved to a source routed elsewhere: the fetch widens to\n // every selected source (never beyond the selection), and the routing\n // check is waived for that card alone. Without a live card, the strict\n // routed-source rule applies.\n const held = await findHeldCard(options, resolved.tenant.orgId, factoryProjectId, identifier, issueId);\n const holdsLiveCard =\n held != null &&\n !(options.boards ? isTerminalWorkItem(options.boards, held) : isTerminalFactoryRuleStage(held.stages));\n if (routedSourceIds.length === 0 && !holdsLiveCard) return c.json({ error: 'issue_not_found' }, 404);\n const fetchSourceIds = holdsLiveCard ? selectedIds : routedSourceIds;\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const issue = await linear.fetchIssueDetail(accessToken, issueReference, selectedIds, fetchSourceIds);\n const matchesReference = issueId !== undefined ? issue?.id === issueId : issue?.identifier === identifier;\n const winningSourceId = issue ? winningLinearSourceId(linear, selectedIds, issue) : null;\n const isRouted = winningSourceId != null && (holdsLiveCard || routedSourceIds.includes(winningSourceId));\n // Reads exactly like an issue that doesn't exist.\n if (!issue || !matchesReference || !isRouted) {\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 linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;;;;AA+BA,MAAM,UAAU;;AAGhB,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;;;;;;;;;;;AAiEA,eAAe,wBAAwB,EACrC,QACA,OACA,kBACA,eAMkC;CAClC,MAAM,WAAW,IAAI,IAAI,WAAW;CACpC,MAAM,eAAuC,CAAC;CAC9C,KAAK,MAAM,WAAW,MAAM,OAAO,aAAa;EAAE;EAAO,eAAe;CAAS,CAAC,GAChF,IAAI,QAAQ,qBAAqB,oBAAoB,QAAQ,SAAS,SAAS,IAAI,QAAQ,QAAQ,GACjG,aAAa,QAAQ,YAAY,QAAQ;CAG7C,OAAO;AACT;;;;;;AAOA,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,IA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W,mBAAmB,SAAS,iBAAiB,gBAAgB,SAAS,eAAe;IAEtG,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC,UAClC,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,iBAAiB,MAAM,CAAC,GAAG,GAAG;GACvC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
@@ -20,6 +20,7 @@ export interface LinearIssueIngress {
20
20
  updatedAt: string;
21
21
  /** Linear source the issue was read from (project or team); resolves the bound board via `intakeBoards`. */
22
22
  sourceId?: string | null;
23
+ projectId?: string | null;
23
24
  }
24
25
  export interface LinearRulesOptions {
25
26
  projects: Pick<FactoryProjectsStorage, 'get'>;
@@ -1 +1 @@
1
- {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/rules.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAG3D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAe,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAC9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAkB3D,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;I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kB;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,kBAAkB,EAAE,CAAC;IAC7B,+EAA+E;IAC/E,YAAY,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACjD;AAED,KAAK,aAAa,GAAG,WAAW,GAAG,UAAU,GAAG,SAAS,CAAC;AAE1D,qBAAa,WAAW;;IACV,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,kBAAkB;IAElD,MAAM,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CAyI9F;AAED,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAA;CAAE,EAC5C,OAAO,EAAE,kBAAkB,GAC1B,CAAC,CAAC,KAAK,EAAE,kBAAkB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAU/D"}
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":["#heldElsewhere","#ingestIssue"],"sources":["../../../src/integrations/linear/rules.ts"],"sourcesContent":["import { boardForWorkItem, isTerminalWorkItem } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport type { FactoryLinearRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { linearClaimKey } from './claim.js';\nimport type { LinearEventRules } 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\nexport interface LinearIssueIngress {\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 Linear user who created the issue, when available. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Linear source the issue was read from (project or team); resolves the bound board via `intakeBoards`. */\n sourceId?: string | null;\n}\n\nexport interface LinearRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry;\n linearRules: LinearEventRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n /** Board id per bound Linear source id, from the project's intake bindings. */\n intakeBoards?: Readonly<Record<string, string>>;\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\nexport class LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\n\n async ingest(input: LinearRulesIngress): 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\n const items = await this.options.storage.list({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const itemsByClaimKey = new Map(items.filter(item => item.claimKey).map(item => [item.claimKey, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // The stable issue id finds the card even after Linear renamed the\n // identifier; the identifier covers cards filed before claims existed.\n const relatedItem =\n itemsByClaimKey.get(linearClaimKey(issue.id)) ?? itemsBySourceKey.get(`linear:${issue.identifier}`);\n // One live card per Linear issue per org. When the winning source for an\n // issue moves to a source routed elsewhere (a project deselected under a\n // selected team, or the reverse), the card that already exists keeps the\n // issue; this Factory must not mint a second one. The store's claim index\n // is the guarantee; this check spares the dispatcher a refused upsert.\n if (!relatedItem && (await this.#heldElsewhere(input, issue))) {\n statuses.push('missing');\n continue;\n }\n statuses.push(await this.#ingestIssue(input, issue, 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 #heldElsewhere(input: LinearRulesIngress, issue: LinearIssueIngress): Promise<boolean> {\n const heldLive = (row: WorkItemRow) =>\n row.factoryProjectId !== input.factoryProjectId && !isTerminalWorkItem(this.options.boards, row);\n const claimant = await this.options.storage.getByClaimKey({\n orgId: input.orgId,\n claimKey: linearClaimKey(issue.id),\n });\n if (claimant && heldLive(claimant)) return true;\n // Cards filed before claims existed carry only the identifier.\n const legacy = await this.options.storage.listBySource({\n orgId: input.orgId,\n source: { integrationId: 'linear', type: 'issue', externalId: `linear:${issue.identifier}` },\n });\n return legacy.some(heldLive);\n }\n\n async #ingestIssue(\n input: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: WorkItemRow | undefined,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${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 boundBoardId = issue.sourceId ? input.intakeBoards?.[issue.sourceId] : undefined;\n const boundBoard = boundBoardId ? this.options.boards.get(boundBoardId) : undefined;\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: `linear.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-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 acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n }\n : {}),\n ...(boundBoard ? { intake: { board: boundBoard.id, initialPhase: boundBoard.initialPhase } } : {}),\n event,\n issue,\n };\n\n const rule = this.options.linearRules[context.event];\n let decision: FactoryRuleDecision | void;\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.options.boards,\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 Linear rule failed.',\n };\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: 'linear.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 return committed.status;\n }\n}\n\nexport function attachLinearRules(\n linear: { readonly rules: LinearEventRules },\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n linearRules: linear.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;AAUA,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;AAwCA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,SAA8C;EAA7B,KAAA,UAAA;CAA8B;CAE3D,MAAM,OAAO,OAAiF;EAE5F,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB,CAAC,GACpF,OAAO;GAAE,QAAQ;GAAW,UAAU;EAAE;EAEtD,MAAM,QAAQ,MAAM,KAAK,QAAQ,QAAQ,KAAK;GAAE,OAAO,MAAM;GAAO,kBAAkB,MAAM;EAAiB,CAAC;EAC9G,MAAM,mBAAmB,IAAI,IAAI,MAAM,KAAI,SAAQ,CAAC,KAAK,gBAAgB,YAAY,IAAI,CAAC,CAAC;EAC3F,MAAM,kBAAkB,IAAI,IAAI,MAAM,QAAO,SAAQ,KAAK,QAAQ,CAAC,CAAC,KAAI,SAAQ,CAAC,KAAK,UAAU,IAAI,CAAC,CAAC;EACtG,MAAM,WAA4B,CAAC;EACnC,KAAK,MAAM,SAAS,MAAM,QAAQ;GAGhC,MAAM,cACJ,gBAAgB,IAAI,eAAe,M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UAAU;IACR,QAAQ;IACR,MAAM,WAAW,YAAY;IAC7B,QAAQ,WACJ,uCACA,iBAAiB,QACf,MAAM,QAAQ,MAAM,GAAG,GAAK,IAC5B;GACR;EACF;EAeA,QAAO,MAbiB,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,aAAa,MAAM;GAC/B,SAAS;IAAE,UAAU;IAAW,aAAa;GAAuB;GACpE,eAAe,KAAK,QAAQ;GAC5B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC,EAAA,CACgB;CACnB;AACF;AAEA,SAAgB,kBACd,QACA,SAC+D;CAC/D,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,YAAY;EAC5B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,aAAa,OAAO;CACtB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
1
+ {"version":3,"file":"rules.js","names":["#heldElsewhere","#ingestIssue"],"sources":["../../../src/integrations/linear/rules.ts"],"sourcesContent":["import { boardForWorkItem, isTerminalWorkItem } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport type { FactoryLinearRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { linearClaimKey } from './claim.js';\nimport type { LinearEventRules } 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\nexport interface LinearIssueIngress {\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 Linear user who created the issue, when available. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Linear source the issue was read from (project or team); resolves the bound board via `intakeBoards`. */\n sourceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface LinearRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry;\n linearRules: LinearEventRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n /** Board id per bound Linear source id, from the project's intake bindings. */\n intakeBoards?: Readonly<Record<string, string>>;\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\nexport class LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\n\n async ingest(input: LinearRulesIngress): 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\n const items = await this.options.storage.list({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const itemsByClaimKey = new Map(items.filter(item => item.claimKey).map(item => [item.claimKey, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // The stable issue id finds the card even after Linear renamed the\n // identifier; the identifier covers cards filed before claims existed.\n const relatedItem =\n itemsByClaimKey.get(linearClaimKey(issue.id)) ?? itemsBySourceKey.get(`linear:${issue.identifier}`);\n // One live card per Linear issue per org. When the winning source for an\n // issue moves to a source routed elsewhere (a project deselected under a\n // selected team, or the reverse), the card that already exists keeps the\n // issue; this Factory must not mint a second one. The store's claim index\n // is the guarantee; this check spares the dispatcher a refused upsert.\n if (!relatedItem && (await this.#heldElsewhere(input, issue))) {\n statuses.push('missing');\n continue;\n }\n statuses.push(await this.#ingestIssue(input, issue, 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 #heldElsewhere(input: LinearRulesIngress, issue: LinearIssueIngress): Promise<boolean> {\n const heldLive = (row: WorkItemRow) =>\n row.factoryProjectId !== input.factoryProjectId && !isTerminalWorkItem(this.options.boards, row);\n const claimant = await this.options.storage.getByClaimKey({\n orgId: input.orgId,\n claimKey: linearClaimKey(issue.id),\n });\n if (claimant && heldLive(claimant)) return true;\n // Cards filed before claims existed carry only the identifier.\n const legacy = await this.options.storage.listBySource({\n orgId: input.orgId,\n source: { integrationId: 'linear', type: 'issue', externalId: `linear:${issue.identifier}` },\n });\n return legacy.some(heldLive);\n }\n\n async #ingestIssue(\n input: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: WorkItemRow | undefined,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${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 boundBoardId = issue.sourceId ? input.intakeBoards?.[issue.sourceId] : undefined;\n const boundBoard = boundBoardId ? this.options.boards.get(boundBoardId) : undefined;\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: `linear.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-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 acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n }\n : {}),\n ...(boundBoard ? { intake: { board: boundBoard.id, initialPhase: boundBoard.initialPhase } } : {}),\n event,\n issue,\n };\n\n const rule = this.options.linearRules[context.event];\n let decision: FactoryRuleDecision | void;\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.options.boards,\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 Linear rule failed.',\n };\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: 'linear.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 return committed.status;\n }\n}\n\nexport function attachLinearRules(\n linear: { readonly rules: LinearEventRules },\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n linearRules: linear.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;AAUA,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;AAyCA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,SAA8C;EAA7B,KAAA,UAAA;CAA8B;CAE3D,MAAM,OAAO,OAAiF;EAE5F,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB,CAAC,GACpF,OAAO;GAAE,QAAQ;GAAW,UAAU;EAAE;EAEtD,MAAM,QAAQ,MAAM,KAAK,QAAQ,QAAQ,KAAK;GAAE,OAAO,MAAM;GAAO,kBAAkB,MAAM;EAAiB,CAAC;EAC9G,MAAM,mBAAmB,IAAI,IAAI,MAAM,KAAI,SAAQ,CAAC,KAAK,gBAAgB,YAAY,IAAI,CAAC,CAAC;EAC3F,MAAM,kBAAkB,IAAI,IAAI,MAAM,QAAO,SAAQ,KAAK,QAAQ,CAAC,CAAC,KAAI,SAAQ,CAAC,KAAK,UAAU,IAAI,CAAC,CAAC;EACtG,MAAM,WAA4B,CAAC;EACnC,KAAK,MAAM,SAAS,MAAM,QAAQ;GAGhC,MAAM,cACJ,gBAAgB,IAAI,eAAe,MAAM,EAAE,CAAC,KAA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R,MAAM,WAAW,YAAY;IAC7B,QAAQ,WACJ,uCACA,iBAAiB,QACf,MAAM,QAAQ,MAAM,GAAG,GAAK,IAC5B;GACR;EACF;EAeA,QAAO,MAbiB,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,aAAa,MAAM;GAC/B,SAAS;IAAE,UAAU;IAAW,aAAa;GAAuB;GACpE,eAAe,KAAK,QAAQ;GAC5B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC,EAAA,CACgB;CACnB;AACF;AAEA,SAAgB,kBACd,QACA,SAC+D;CAC/D,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,YAAY;EAC5B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,aAAa,OAAO;CACtB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"event-worker.js","names":["#client","#linear","#storage","#projects","#workItems","#ingestFactoryIssue","#reconcileFactoryState","#pollEventsEnabled","#intervalMs","#reconcileIntervalMs","#now","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#pollWorkspace","#maybeReconcile","#lastReconcileAt","#saveSettings","#dispatchEvent"],"sources":["../../../../src/integrations/platform/linear/event-worker.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport type { IssueReconciler } from '../../issue-reconciler.js';\nimport type { LinearIssueIngress, LinearRulesIngress } from '../../linear/rules.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/linear';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\nconst DEFAULT_RECONCILE_INTERVAL_MS = 5 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_linear_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst LEASE_KEY = 'platform-linear-events:linear';\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformLinearEventWorkerSettings = {\n version: 1;\n workspaces: Record<string, EventCursor>;\n};\n\nexport type PlatformLinearEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformLinearEventWorkerSettings,\n Record<string, unknown>\n>;\n\n/**\n * Minimal envelope shape mirrored from `@platform/linear`. Kept opaque\n * (`data: unknown`) — every consumer demuxes by `type`.\n */\nexport interface LinearWebhookEnvelope {\n type: string;\n action: string | null;\n createdAt: string | null;\n webhookTimestamp: number | null;\n linearOrganizationId: string | null;\n oauthClientId: string | null;\n url: string | null;\n data: unknown;\n}\n\nexport interface LinearEventLogEntry {\n id: string;\n timestamp: number;\n envelope: LinearWebhookEnvelope;\n}\n\nexport interface PlatformLinearWorkspace {\n linearWorkspaceId: string;\n linearWorkspaceName?: string;\n}\n\n/**\n * Everything the worker needs to drive ingest + reconciliation without\n * pulling in the full `PlatformLinearIntegration` type (circular).\n */\nexport interface PlatformLinearEventDispatchIntegration {\n listWorkspaces(): Promise<PlatformLinearWorkspace[]>;\n}\n\nexport interface PlatformLinearEventWorkerConfig {\n client: PlatformApiClient;\n linear: PlatformLinearEventDispatchIntegration;\n storage: PlatformLinearEventStorage;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n /**\n * Used to scope event dispatch to `(orgId, factoryProjectId)` pairs that\n * already have a work item linked to the incoming Linear issue. Without\n * this scoping, a workspace-scoped event would fan out to every project in\n * every org and materialize a triage card in each — a cross-tenant leak.\n * First-observation of a Linear issue happens through the user-authenticated\n * `/web/linear/issues?factoryProjectId=...` intake path instead.\n */\n workItems: Pick<WorkItemsStorage, 'list'>;\n /** Called with a single-issue rules ingress derived from an `Issue` webhook. */\n ingestFactoryIssue?: (input: LinearRulesIngress) => Promise<unknown>;\n reconcileFactoryState?: IssueReconciler;\n /** When false the worker skips event tailing and only runs the reconcile sweep. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n reconcileIntervalMs?: number;\n now?: () => number;\n}\n\n/**\n * Tails the Platform Linear event stream (Redis-backed, per workspace) and\n * runs the same folded issue-reconcile sweep pattern as\n * `PlatformGithubEventWorker`. Issue events are translated into a normal\n * `LinearRulesIngress` so downstream rule dispatch is identical to the\n * polling path.\n *\n * Cursor state is persisted per workspace via the integration's generic\n * settings surface, keyed by a well-known worker identity. Cold start uses\n * `afterTimestamp: now - 1` to avoid replaying the 14-day stream backlog.\n *\n * ## Delivery semantics\n *\n * **At-most-once** per event. The cursor advances to the last event ID in a\n * page after all dispatch attempts on that page complete, regardless of\n * whether individual ingest calls threw. Ingest failures are logged, the\n * offending event is not retried, and drift is caught by the folded\n * `LinearIssueReconciler` sweep on its own cadence (default 5 minutes). This\n * matches `PlatformGithubEventWorker` and avoids poison-pill events blocking\n * the whole stream. Any consumer that needs exactly-once must idempotently\n * handle the same issue arriving via both the event path and the reconcile\n * path.\n */\nexport class PlatformLinearEventWorker extends MastraWorker {\n readonly name = 'platform-linear-events';\n\n readonly #client: PlatformApiClient;\n readonly #linear: PlatformLinearEventDispatchIntegration;\n readonly #storage: PlatformLinearEventStorage;\n readonly #projects: Pick<FactoryProjectsStorage, 'listAll'>;\n readonly #workItems: Pick<WorkItemsStorage, 'list'>;\n readonly #ingestFactoryIssue: ((input: LinearRulesIngress) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: IssueReconciler | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #intervalMs: number;\n readonly #reconcileIntervalMs: number;\n readonly #now: () => number;\n readonly #leaseOwner = randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n #lastReconcileAt = 0;\n #settings: PlatformLinearEventWorkerSettings = { version: 1, workspaces: {} };\n\n constructor(config: PlatformLinearEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#linear = config.linear;\n this.#storage = config.storage;\n this.#projects = config.projects;\n this.#workItems = config.workItems;\n this.#ingestFactoryIssue = config.ingestFactoryIssue;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.#reconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform Linear event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#reconcileIntervalMs) || this.#reconcileIntervalMs <= 0) {\n throw new Error('Platform Linear reconcile interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n this.#now = config.now ?? Date.now;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformLinearEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform Linear event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(LEASE_KEY, this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform Linear event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform Linear event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n // Reconcile-only mode has no event tail to keep fresh, so tick on the\n // slower reconcile cadence instead of the polling interval.\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileIntervalMs;\n\n if (this.#pollEventsEnabled) {\n // Only list workspaces when actually tailing events: reconciliation\n // does not need the workspace list, and folding this call into\n // reconcile-only mode would let one workspace-listing outage take\n // down the reconcile sweep as well.\n let workspaces: PlatformLinearWorkspace[] = [];\n try {\n workspaces = await this.#linear.listWorkspaces();\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace listing failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n }\n\n for (const workspace of workspaces) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollWorkspace(workspace.linearWorkspaceId);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace event polling failed', {\n linearWorkspaceId: workspace.linearWorkspaceId,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile();\n\n return retryInMs;\n }\n\n async #maybeReconcile(): Promise<void> {\n if (!this.#reconcileFactoryState || !this.#running || !this.#hasLease) return;\n const now = this.#now();\n if (now - this.#lastReconcileAt < this.#reconcileIntervalMs) return;\n // Advance the clock before sweeping so a persistently failing sweep stays\n // on cadence instead of retrying every poll tick.\n this.#lastReconcileAt = now;\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState();\n const context = { ...counts, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform Linear issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform Linear issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform Linear issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue reconcile failed', {\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n async #pollWorkspace(linearWorkspaceId: string): Promise<void> {\n if (!this.#settings.workspaces[linearWorkspaceId]) {\n this.#settings.workspaces[linearWorkspaceId] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.workspaces[linearWorkspaceId]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE), type: 'Issue' });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('after', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: LinearEventLogEntry[] }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(linearWorkspaceId)}/events?${query}`,\n );\n this.deps?.logger.debug('Platform Linear workspace event poll completed', {\n linearWorkspaceId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0) return;\n\n const lastId = page.events[page.events.length - 1]!.id;\n\n // Resolve the project set once per page instead of once per event.\n // The event stream can return up to EVENT_PAGE_SIZE (500) events; the\n // project list rarely changes within the second or two it takes to\n // dispatch a single page, and #dispatchEvent still consults storage\n // per-project to check for a linked work item.\n const projects = await this.#projects.listAll();\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n await this.#dispatchEvent(linearWorkspaceId, event, projects);\n }\n\n if ('afterEventId' in cursor && cursor.afterEventId === lastId) return;\n this.#settings.workspaces[linearWorkspaceId] = { afterEventId: lastId };\n await this.#saveSettings();\n\n // Short pages mean we've caught up; wait for the next tick.\n if (page.events.length < EVENT_PAGE_SIZE) return;\n }\n }\n\n async #dispatchEvent(\n linearWorkspaceId: string,\n event: LinearEventLogEntry,\n projects: readonly { id: string; orgId: string }[],\n ): Promise<void> {\n if (event.envelope.type !== 'Issue') return;\n if (!this.#ingestFactoryIssue) return;\n const issue = parseIssueEnvelope(event.envelope);\n if (!issue) {\n this.deps?.logger.warn('Platform Linear event log returned an unusable Issue payload', {\n linearWorkspaceId,\n eventId: event.id,\n });\n return;\n }\n\n // The event stream is workspace-scoped and Platform Linear has no\n // workspace→org mapping we can trust. To avoid cross-tenant fan-out (an\n // Issue from org A materializing a triage card in org B via the default\n // `linearIssueObserved` rule), only dispatch to `(orgId, factoryProjectId)`\n // pairs that already have a persisted work item for this Linear issue.\n // First-observation of a Linear issue happens through the\n // user-authenticated `/web/linear/issues?factoryProjectId=...` intake path.\n const sourceKey = `linear:${issue.identifier}`;\n let dispatched = 0;\n for (const project of projects) {\n let items;\n try {\n items = await this.#workItems.list({ orgId: project.orgId, factoryProjectId: project.id });\n } catch (error) {\n this.deps?.logger.error('Platform Linear work-item lookup failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const linked = items.some(\n item =>\n item.externalSource?.integrationId === 'linear' &&\n item.externalSource.type === 'issue' &&\n item.externalSource.externalId === sourceKey,\n );\n if (!linked) continue;\n try {\n await this.#ingestFactoryIssue({\n orgId: project.orgId,\n userId: 'platform-linear-event-worker',\n factoryProjectId: project.id,\n issues: [issue],\n });\n dispatched += 1;\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue ingest failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (dispatched === 0) {\n this.deps?.logger.debug('Platform Linear Issue event had no linked work items to update', {\n linearWorkspaceId,\n eventId: event.id,\n sourceKey,\n });\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformLinearEventWorkerSettings | null): PlatformLinearEventWorkerSettings {\n if (!value || value.version !== 1 || !value.workspaces || typeof value.workspaces !== 'object') {\n return { version: 1, workspaces: {} };\n }\n return { version: 1, workspaces: { ...value.workspaces } };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n\n/**\n * Translate an Issue webhook envelope into the rules-ingress shape.\n * Returns undefined when the payload lacks the identifiers we need to\n * match a work item.\n */\nfunction parseIssueEnvelope(envelope: LinearWebhookEnvelope): LinearIssueIngress | undefined {\n const data = envelope.data;\n if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;\n const raw = data as Record<string, unknown>;\n const id = typeof raw.id === 'string' ? raw.id : undefined;\n const identifier = typeof raw.identifier === 'string' ? raw.identifier : undefined;\n const title = typeof raw.title === 'string' ? raw.title : undefined;\n const url = typeof raw.url === 'string' ? raw.url : envelope.url ?? undefined;\n if (!id || !identifier || !title || !url) return undefined;\n\n const state = optionalObject(raw.state);\n const team = optionalObject(raw.team);\n const assignee = optionalObject(raw.assignee);\n const creator = optionalObject(raw.user) ?? optionalObject(raw.creator);\n const labels = Array.isArray(raw.labels)\n ? raw.labels.flatMap(label => {\n const obj = optionalObject(label);\n return obj && typeof obj.name === 'string' ? [obj.name] : [];\n })\n : [];\n\n const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : envelope.createdAt ?? '';\n const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;\n\n return {\n id,\n identifier,\n title,\n url,\n state: (state && typeof state.name === 'string' ? state.name : null) ?? '',\n stateType: (state && typeof state.type === 'string' ? state.type : null) ?? '',\n priorityLabel: typeof raw.priorityLabel === 'string' ? raw.priorityLabel : '',\n assignee: assignee && typeof assignee.name === 'string' ? assignee.name : null,\n creator: creator && typeof creator.name === 'string' ? creator.name : null,\n team: team && typeof team.name === 'string' ? team.name : null,\n labels,\n createdAt,\n updatedAt,\n };\n}\n\nfunction optionalObject(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n"],"mappings":";;;;;AAcA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AACjC,MAAM,gCAAgC,IAAI;AAC1C,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;AA+FlB,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW;CAElC,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC;CACA,YAAY;CACZ,aAAa;CACb,mBAAmB;CACnB,YAA+C;EAAE,SAAS;EAAG,YAAY,CAAC;CAAE;CAE5E,YAAY,QAAyC;EACnD,MAAM;EACN,KAAKA,UAAU,OAAO;EACtB,KAAKC,UAAU,OAAO;EACtB,KAAKC,WAAW,OAAO;EACvB,KAAKC,YAAY,OAAO;EACxB,KAAKC,aAAa,OAAO;EACzB,KAAKC,sBAAsB,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KAAK,SAAS,WAAW,KAAK,OAAO;EAC1D;EACA;EACA;CACF;AACF;AAEA,SAAS,eAAe,OAAqD;CAC3E,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO,KAAA;CACxE,OAAO;AACT"}
1
+ {"version":3,"file":"event-worker.js","names":["#client","#linear","#storage","#projects","#workItems","#ingestFactoryIssue","#reconcileFactoryState","#pollEventsEnabled","#intervalMs","#reconcileIntervalMs","#now","#leaseOwner","#leaseTtlMs","#leaseProvider","#running","#startedAt","#settings","#schedule","#timer","#stopLeaseRenewal","#inFlight","#hasLease","#tick","#ensureLease","#poll","#startLeaseRenewal","#leaseRenewalTimer","#pollWorkspace","#maybeReconcile","#lastReconcileAt","#saveSettings","#dispatchEvent"],"sources":["../../../../src/integrations/platform/linear/event-worker.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport type { IssueReconciler } from '../../issue-reconciler.js';\nimport type { LinearIssueIngress, LinearRulesIngress } from '../../linear/rules.js';\nimport { PlatformApiClient, PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/linear';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\nconst DEFAULT_RECONCILE_INTERVAL_MS = 5 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_linear_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst LEASE_KEY = 'platform-linear-events:linear';\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformLinearEventWorkerSettings = {\n version: 1;\n workspaces: Record<string, EventCursor>;\n};\n\nexport type PlatformLinearEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformLinearEventWorkerSettings,\n Record<string, unknown>\n>;\n\n/**\n * Minimal envelope shape mirrored from `@platform/linear`. Kept opaque\n * (`data: unknown`) — every consumer demuxes by `type`.\n */\nexport interface LinearWebhookEnvelope {\n type: string;\n action: string | null;\n createdAt: string | null;\n webhookTimestamp: number | null;\n linearOrganizationId: string | null;\n oauthClientId: string | null;\n url: string | null;\n data: unknown;\n}\n\nexport interface LinearEventLogEntry {\n id: string;\n timestamp: number;\n envelope: LinearWebhookEnvelope;\n}\n\nexport interface PlatformLinearWorkspace {\n linearWorkspaceId: string;\n linearWorkspaceName?: string;\n}\n\n/**\n * Everything the worker needs to drive ingest + reconciliation without\n * pulling in the full `PlatformLinearIntegration` type (circular).\n */\nexport interface PlatformLinearEventDispatchIntegration {\n listWorkspaces(): Promise<PlatformLinearWorkspace[]>;\n}\n\nexport interface PlatformLinearEventWorkerConfig {\n client: PlatformApiClient;\n linear: PlatformLinearEventDispatchIntegration;\n storage: PlatformLinearEventStorage;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n /**\n * Used to scope event dispatch to `(orgId, factoryProjectId)` pairs that\n * already have a work item linked to the incoming Linear issue. Without\n * this scoping, a workspace-scoped event would fan out to every project in\n * every org and materialize a triage card in each — a cross-tenant leak.\n * First-observation of a Linear issue happens through the user-authenticated\n * `/web/linear/issues?factoryProjectId=...` intake path instead.\n */\n workItems: Pick<WorkItemsStorage, 'list'>;\n /** Called with a single-issue rules ingress derived from an `Issue` webhook. */\n ingestFactoryIssue?: (input: LinearRulesIngress) => Promise<unknown>;\n reconcileFactoryState?: IssueReconciler;\n /** When false the worker skips event tailing and only runs the reconcile sweep. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n reconcileIntervalMs?: number;\n now?: () => number;\n}\n\n/**\n * Tails the Platform Linear event stream (Redis-backed, per workspace) and\n * runs the same folded issue-reconcile sweep pattern as\n * `PlatformGithubEventWorker`. Issue events are translated into a normal\n * `LinearRulesIngress` so downstream rule dispatch is identical to the\n * polling path.\n *\n * Cursor state is persisted per workspace via the integration's generic\n * settings surface, keyed by a well-known worker identity. Cold start uses\n * `afterTimestamp: now - 1` to avoid replaying the 14-day stream backlog.\n *\n * ## Delivery semantics\n *\n * **At-most-once** per event. The cursor advances to the last event ID in a\n * page after all dispatch attempts on that page complete, regardless of\n * whether individual ingest calls threw. Ingest failures are logged, the\n * offending event is not retried, and drift is caught by the folded\n * `LinearIssueReconciler` sweep on its own cadence (default 5 minutes). This\n * matches `PlatformGithubEventWorker` and avoids poison-pill events blocking\n * the whole stream. Any consumer that needs exactly-once must idempotently\n * handle the same issue arriving via both the event path and the reconcile\n * path.\n */\nexport class PlatformLinearEventWorker extends MastraWorker {\n readonly name = 'platform-linear-events';\n\n readonly #client: PlatformApiClient;\n readonly #linear: PlatformLinearEventDispatchIntegration;\n readonly #storage: PlatformLinearEventStorage;\n readonly #projects: Pick<FactoryProjectsStorage, 'listAll'>;\n readonly #workItems: Pick<WorkItemsStorage, 'list'>;\n readonly #ingestFactoryIssue: ((input: LinearRulesIngress) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: IssueReconciler | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #intervalMs: number;\n readonly #reconcileIntervalMs: number;\n readonly #now: () => number;\n readonly #leaseOwner = randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n #lastReconcileAt = 0;\n #settings: PlatformLinearEventWorkerSettings = { version: 1, workspaces: {} };\n\n constructor(config: PlatformLinearEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#linear = config.linear;\n this.#storage = config.storage;\n this.#projects = config.projects;\n this.#workItems = config.workItems;\n this.#ingestFactoryIssue = config.ingestFactoryIssue;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n this.#reconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform Linear event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#reconcileIntervalMs) || this.#reconcileIntervalMs <= 0) {\n throw new Error('Platform Linear reconcile interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n this.#now = config.now ?? Date.now;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformLinearEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform Linear event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(LEASE_KEY, this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform Linear event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(LEASE_KEY, this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform Linear event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n // Reconcile-only mode has no event tail to keep fresh, so tick on the\n // slower reconcile cadence instead of the polling interval.\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileIntervalMs;\n\n if (this.#pollEventsEnabled) {\n // Only list workspaces when actually tailing events: reconciliation\n // does not need the workspace list, and folding this call into\n // reconcile-only mode would let one workspace-listing outage take\n // down the reconcile sweep as well.\n let workspaces: PlatformLinearWorkspace[] = [];\n try {\n workspaces = await this.#linear.listWorkspaces();\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace listing failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n }\n\n for (const workspace of workspaces) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollWorkspace(workspace.linearWorkspaceId);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Linear workspace event polling failed', {\n linearWorkspaceId: workspace.linearWorkspaceId,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile();\n\n return retryInMs;\n }\n\n async #maybeReconcile(): Promise<void> {\n if (!this.#reconcileFactoryState || !this.#running || !this.#hasLease) return;\n const now = this.#now();\n if (now - this.#lastReconcileAt < this.#reconcileIntervalMs) return;\n // Advance the clock before sweeping so a persistently failing sweep stays\n // on cadence instead of retrying every poll tick.\n this.#lastReconcileAt = now;\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState();\n const context = { ...counts, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform Linear issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform Linear issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform Linear issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue reconcile failed', {\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n async #pollWorkspace(linearWorkspaceId: string): Promise<void> {\n if (!this.#settings.workspaces[linearWorkspaceId]) {\n this.#settings.workspaces[linearWorkspaceId] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.workspaces[linearWorkspaceId]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE), type: 'Issue' });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('after', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: LinearEventLogEntry[] }>(\n 'GET',\n `${API_PREFIX}/workspaces/${encodeURIComponent(linearWorkspaceId)}/events?${query}`,\n );\n this.deps?.logger.debug('Platform Linear workspace event poll completed', {\n linearWorkspaceId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0) return;\n\n const lastId = page.events[page.events.length - 1]!.id;\n\n // Resolve the project set once per page instead of once per event.\n // The event stream can return up to EVENT_PAGE_SIZE (500) events; the\n // project list rarely changes within the second or two it takes to\n // dispatch a single page, and #dispatchEvent still consults storage\n // per-project to check for a linked work item.\n const projects = await this.#projects.listAll();\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n await this.#dispatchEvent(linearWorkspaceId, event, projects);\n }\n\n if ('afterEventId' in cursor && cursor.afterEventId === lastId) return;\n this.#settings.workspaces[linearWorkspaceId] = { afterEventId: lastId };\n await this.#saveSettings();\n\n // Short pages mean we've caught up; wait for the next tick.\n if (page.events.length < EVENT_PAGE_SIZE) return;\n }\n }\n\n async #dispatchEvent(\n linearWorkspaceId: string,\n event: LinearEventLogEntry,\n projects: readonly { id: string; orgId: string }[],\n ): Promise<void> {\n if (event.envelope.type !== 'Issue') return;\n if (!this.#ingestFactoryIssue) return;\n const issue = parseIssueEnvelope(event.envelope);\n if (!issue) {\n this.deps?.logger.warn('Platform Linear event log returned an unusable Issue payload', {\n linearWorkspaceId,\n eventId: event.id,\n });\n return;\n }\n\n // The event stream is workspace-scoped and Platform Linear has no\n // workspace→org mapping we can trust. To avoid cross-tenant fan-out (an\n // Issue from org A materializing a triage card in org B via the default\n // `linearIssueObserved` rule), only dispatch to `(orgId, factoryProjectId)`\n // pairs that already have a persisted work item for this Linear issue.\n // First-observation of a Linear issue happens through the\n // user-authenticated `/web/linear/issues?factoryProjectId=...` intake path.\n const sourceKey = `linear:${issue.identifier}`;\n let dispatched = 0;\n for (const project of projects) {\n let items;\n try {\n items = await this.#workItems.list({ orgId: project.orgId, factoryProjectId: project.id });\n } catch (error) {\n this.deps?.logger.error('Platform Linear work-item lookup failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const linked = items.some(\n item =>\n item.externalSource?.integrationId === 'linear' &&\n item.externalSource.type === 'issue' &&\n item.externalSource.externalId === sourceKey,\n );\n if (!linked) continue;\n try {\n await this.#ingestFactoryIssue({\n orgId: project.orgId,\n userId: 'platform-linear-event-worker',\n factoryProjectId: project.id,\n issues: [issue],\n });\n dispatched += 1;\n } catch (error) {\n this.deps?.logger.error('Platform Linear issue ingest failed', {\n linearWorkspaceId,\n eventId: event.id,\n projectId: project.id,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (dispatched === 0) {\n this.deps?.logger.debug('Platform Linear Issue event had no linked work items to update', {\n linearWorkspaceId,\n eventId: event.id,\n sourceKey,\n });\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformLinearEventWorkerSettings | null): PlatformLinearEventWorkerSettings {\n if (!value || value.version !== 1 || !value.workspaces || typeof value.workspaces !== 'object') {\n return { version: 1, workspaces: {} };\n }\n return { version: 1, workspaces: { ...value.workspaces } };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n\n/**\n * Translate an Issue webhook envelope into the rules-ingress shape.\n * Returns undefined when the payload lacks the identifiers we need to\n * match a work item.\n */\nfunction parseIssueEnvelope(envelope: LinearWebhookEnvelope): LinearIssueIngress | undefined {\n const data = envelope.data;\n if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;\n const raw = data as Record<string, unknown>;\n const id = typeof raw.id === 'string' ? raw.id : undefined;\n const identifier = typeof raw.identifier === 'string' ? raw.identifier : undefined;\n const title = typeof raw.title === 'string' ? raw.title : undefined;\n const url = typeof raw.url === 'string' ? raw.url : (envelope.url ?? undefined);\n if (!id || !identifier || !title || !url) return undefined;\n\n const state = optionalObject(raw.state);\n const team = optionalObject(raw.team);\n const assignee = optionalObject(raw.assignee);\n const creator = optionalObject(raw.user) ?? optionalObject(raw.creator);\n const labels = Array.isArray(raw.labels)\n ? raw.labels.flatMap(label => {\n const obj = optionalObject(label);\n return obj && typeof obj.name === 'string' ? [obj.name] : [];\n })\n : [];\n\n const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : (envelope.createdAt ?? '');\n const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;\n\n return {\n id,\n identifier,\n title,\n url,\n state: (state && typeof state.name === 'string' ? state.name : null) ?? '',\n stateType: (state && typeof state.type === 'string' ? state.type : null) ?? '',\n priorityLabel: typeof raw.priorityLabel === 'string' ? raw.priorityLabel : '',\n assignee: assignee && typeof assignee.name === 'string' ? assignee.name : null,\n creator: creator && typeof creator.name === 'string' ? creator.name : null,\n team: team && typeof team.name === 'string' ? team.name : null,\n labels,\n createdAt,\n updatedAt,\n };\n}\n\nfunction optionalObject(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n return value as Record<string, unknown>;\n}\n"],"mappings":";;;;;AAcA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AACjC,MAAM,gCAAgC,IAAI;AAC1C,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;AA+FlB,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW;CAElC,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC;CACA,YAAY;CACZ,aAAa;CACb,mBAAmB;CACnB,YAA+C;EAAE,SAAS;EAAG,YAAY,CAAC;CAAE;CAE5E,YAAY,QAAyC;EACnD,MAAM;EACN,KAAKA,UAAU,OAAO;EACtB,KAAKC,UAAU,OAAO;EACtB,KAAKC,WAAW,OAAO;EACvB,KAAKC,YAAY,OAAO;EACxB,KAAKC,aAAa,OAAO;EACzB,KAAKC,sBAAsB,OAAO;EAClC,KAAKC,yBAAyB,OAAO;EACrC,KAAKC,qBAAqB,OAAO,qBAAqB;EACtD,KAAKC,cAAc,OAAO,cAAc;EACxC,KAAKC,uBAAuB,OAAO,uBAAuB;EAC1D,IAAI,CAAC,OAAO,SAAS,KAAKD,WAAW,KAAK,KAAKA,eAAe,GAC5D,MAAM,IAAI,MAAM,mEAAmE;EAErF,IAAI,CAAC,OAAO,SAAS,KAAKC,oBAAoB,KAAK,KAAKA,wBAAwB,GAC9E,MAAM,IAAI,MAAM,+DAA+D;EAEjF,KAAKG,cAAc,KAAK,IAAI,kBAAkB,KAAKJ,cAAc,CAAC;EAClE,KAAKE,OAAO,OAAO,OAAO,KAAK;CACjC;CAEA,MAAM,KAAK,MAAiC;EAC1C,MAAM,MAAM,KAAK,IAAI;EACrB,KAAKG,iBAAiB,iBAAiB,KA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