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

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 (121) 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/transition-policy.d.ts +3 -3
  5. package/dist/boards/transition-policy.d.ts.map +1 -1
  6. package/dist/boards/transition-policy.js.map +1 -1
  7. package/dist/boards/work-transition-policy.d.ts.map +1 -1
  8. package/dist/boards/work-transition-policy.js +3 -3
  9. package/dist/boards/work-transition-policy.js.map +1 -1
  10. package/dist/capabilities/intake.d.ts +2 -0
  11. package/dist/capabilities/intake.d.ts.map +1 -1
  12. package/dist/factory.d.ts.map +1 -1
  13. package/dist/factory.js +9 -1
  14. package/dist/factory.js.map +1 -1
  15. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  16. package/dist/integrations/github/default-rules.js +2 -0
  17. package/dist/integrations/github/default-rules.js.map +1 -1
  18. package/dist/integrations/github/routes.d.ts.map +1 -1
  19. package/dist/integrations/github/routes.js +1 -0
  20. package/dist/integrations/github/routes.js.map +1 -1
  21. package/dist/integrations/github/rules.d.ts.map +1 -1
  22. package/dist/integrations/github/rules.js +20 -1
  23. package/dist/integrations/github/rules.js.map +1 -1
  24. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  25. package/dist/integrations/gitlab/routes.js +1 -0
  26. package/dist/integrations/gitlab/routes.js.map +1 -1
  27. package/dist/integrations/linear/default-rules.d.ts +2 -1
  28. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  29. package/dist/integrations/linear/default-rules.js +1 -0
  30. package/dist/integrations/linear/default-rules.js.map +1 -1
  31. package/dist/integrations/linear/integration.d.ts.map +1 -1
  32. package/dist/integrations/linear/integration.js +2 -0
  33. package/dist/integrations/linear/integration.js.map +1 -1
  34. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  35. package/dist/integrations/linear/issue-reconciler.js +3 -0
  36. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  37. package/dist/integrations/linear/routes.d.ts.map +1 -1
  38. package/dist/integrations/linear/routes.js +2 -1
  39. package/dist/integrations/linear/routes.js.map +1 -1
  40. package/dist/integrations/linear/rules.d.ts +1 -0
  41. package/dist/integrations/linear/rules.d.ts.map +1 -1
  42. package/dist/integrations/linear/rules.js.map +1 -1
  43. package/dist/integrations/slack/slack.d.ts +7 -7
  44. package/dist/integrations/slack/slack.d.ts.map +1 -1
  45. package/dist/integrations/slack/slack.js +13 -11
  46. package/dist/integrations/slack/slack.js.map +1 -1
  47. package/dist/platform-auth-host.d.ts +4 -0
  48. package/dist/platform-auth-host.d.ts.map +1 -0
  49. package/dist/platform-auth-host.js +18 -0
  50. package/dist/platform-auth-host.js.map +1 -0
  51. package/dist/routes/intake.d.ts.map +1 -1
  52. package/dist/routes/intake.js +15 -1
  53. package/dist/routes/intake.js.map +1 -1
  54. package/dist/routes/surface.d.ts +1 -1
  55. package/dist/routes/surface.d.ts.map +1 -1
  56. package/dist/routes/surface.js +47 -6
  57. package/dist/routes/surface.js.map +1 -1
  58. package/dist/routes/work-items.d.ts.map +1 -1
  59. package/dist/routes/work-items.js +6 -1
  60. package/dist/routes/work-items.js.map +1 -1
  61. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  62. package/dist/rules/dispatch-errors.js +4 -0
  63. package/dist/rules/dispatch-errors.js.map +1 -1
  64. package/dist/rules/dispatcher.d.ts.map +1 -1
  65. package/dist/rules/dispatcher.js +8 -6
  66. package/dist/rules/dispatcher.js.map +1 -1
  67. package/dist/rules/processor.d.ts.map +1 -1
  68. package/dist/rules/processor.js +9 -1
  69. package/dist/rules/processor.js.map +1 -1
  70. package/dist/rules/review-source-tool.d.ts +103 -0
  71. package/dist/rules/review-source-tool.d.ts.map +1 -0
  72. package/dist/rules/review-source-tool.js +109 -0
  73. package/dist/rules/review-source-tool.js.map +1 -0
  74. package/dist/rules/start-coordinator.d.ts +7 -1
  75. package/dist/rules/start-coordinator.d.ts.map +1 -1
  76. package/dist/rules/start-coordinator.js +56 -2
  77. package/dist/rules/start-coordinator.js.map +1 -1
  78. package/dist/rules/transition-service.d.ts +4 -4
  79. package/dist/rules/transition-service.d.ts.map +1 -1
  80. package/dist/rules/transition-service.js +3 -2
  81. package/dist/rules/transition-service.js.map +1 -1
  82. package/dist/rules/types.d.ts +2 -0
  83. package/dist/rules/types.d.ts.map +1 -1
  84. package/dist/rules/types.js.map +1 -1
  85. package/dist/session/factory-session.d.ts +8 -4
  86. package/dist/session/factory-session.d.ts.map +1 -1
  87. package/dist/session/factory-session.js +4 -2
  88. package/dist/session/factory-session.js.map +1 -1
  89. package/dist/session/work-item-repository.d.ts +21 -0
  90. package/dist/session/work-item-repository.d.ts.map +1 -0
  91. package/dist/session/work-item-repository.js +91 -0
  92. package/dist/session/work-item-repository.js.map +1 -0
  93. package/dist/skills/service.d.ts.map +1 -1
  94. package/dist/skills/service.js +16 -6
  95. package/dist/skills/service.js.map +1 -1
  96. package/dist/storage/domains/intake/base.d.ts +1 -0
  97. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  98. package/dist/storage/domains/intake/base.js.map +1 -1
  99. package/dist/storage/domains/work-items/base.d.ts +13 -2
  100. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  101. package/dist/storage/domains/work-items/base.js +17 -0
  102. package/dist/storage/domains/work-items/base.js.map +1 -1
  103. package/dist/supervisor/session-messaging.d.ts +4 -1
  104. package/dist/supervisor/session-messaging.d.ts.map +1 -1
  105. package/dist/supervisor/session-messaging.js +8 -2
  106. package/dist/supervisor/session-messaging.js.map +1 -1
  107. package/dist/supervisor/write-tools.d.ts +2 -1
  108. package/dist/supervisor/write-tools.d.ts.map +1 -1
  109. package/dist/supervisor/write-tools.js +9 -2
  110. package/dist/supervisor/write-tools.js.map +1 -1
  111. package/dist/workspace.d.ts +7 -1
  112. package/dist/workspace.d.ts.map +1 -1
  113. package/dist/workspace.js +45 -7
  114. package/dist/workspace.js.map +1 -1
  115. package/factory-skills/factory-complete-issue/SKILL.md +4 -2
  116. package/factory-skills/factory-gitlab-rereview/SKILL.md +3 -2
  117. package/factory-skills/factory-gitlab-review/SKILL.md +17 -1
  118. package/factory-skills/factory-plan/SKILL.md +11 -0
  119. package/factory-skills/factory-rereview/SKILL.md +25 -4
  120. package/factory-skills/factory-review/SKILL.md +25 -4
  121. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"integration.js","names":["#storage","#projects","#auth","#updateTokens","#inflightRefreshes","#connectionChecks","#orgIdByResourceId","#resolveIntakeDispatch","#listIntakeIssues","#getIntakeIssue","#createIntakeComment","#updateIntakeIssue","#clientId","#clientSecret","#rules","#requestTokens","#listTeamWorkflowStates","#fetchRemainingIssueComments"],"sources":["../../../src/integrations/linear/integration.ts"],"sourcesContent":["/**\n * `LinearIntegration` — the self-contained Linear integration.\n *\n * Implements the system-wide `FactoryIntegration` contract\n * (`../factory-integration.ts`): the deploy entry reads the Linear OAuth env\n * vars ONCE, constructs an instance with explicit credentials, and passes it\n * to `MastraFactory`. Everything Linear-flavored the system does — the OAuth\n * connect/callback flow, workspace/project/issue reads for Intake, and the\n * agent's issue tools — flows through this instance. No other module reads\n * `LINEAR_*` env vars.\n *\n * The class owns:\n * - OAuth: the user-facing authorize URL, code exchange, and refresh-token\n * rotation against Linear's `/oauth/token` endpoint.\n * - GraphQL reads/writes: viewer workspace, projects, active issues for\n * Intake, full issue detail (description + discussion), issue comments.\n * - The HTTP surface (`routes()`) and per-request agent tools\n * (`agentTools()`), delegating to `./routes.ts` / `./agent-tools.ts` with\n * `this` as the API client.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n ListIntakeIssuesInput,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntegrationStorageHandle } from '../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { buildLinearAgentTools } from './agent-tools.js';\nimport type { LinearEventRules, LinearRuleOverrides } from './default-rules.js';\nimport { resolveLinearRules } from './default-rules.js';\nimport { attachLinearIssueReconciler } from './issue-reconciler.js';\nimport { linearIssueReconciliationEnabled, linearIssueReconciliationInterval } from './reconciliation-config.js';\nimport { buildLinearRoutes } from './routes.js';\nimport { attachLinearRules } from './rules.js';\nimport type { LinearConnectionRow, LinearStorageHandle, UpsertLinearConnectionInput } from './storage.js';\n\nconst LINEAR_GRAPHQL_URL = 'https://api.linear.app/graphql';\nconst LINEAR_TOKEN_URL = 'https://api.linear.app/oauth/token';\nconst LINEAR_AUTHORIZE_URL = 'https://linear.app/oauth/authorize';\n\n/** Credentials and optional event rules for the Linear OAuth application. */\nexport interface LinearIntegrationConfig {\n /** Per-event replacements; omitted events retain defaults, null disables. */\n rules?: LinearRuleOverrides;\n /** OAuth client id of the Linear application. */\n clientId: string;\n /** OAuth client secret of the Linear application. */\n clientSecret: string;\n}\n\n/**\n * Tokens minted by Linear's `/oauth/token` endpoint. Linear access tokens\n * expire (24h) and refresh tokens rotate: every refresh invalidates the old\n * pair, so callers must persist the whole set after each exchange.\n */\nexport interface LinearTokenSet {\n accessToken: string;\n /** Null when Linear issued no refresh token (legacy non-expiring apps). */\n refreshToken: string | null;\n /** Null when Linear reported no `expires_in`. */\n expiresAt: Date | null;\n /** Scopes granted to the token as reported by Linear; null when omitted. */\n scope: string | null;\n}\n\nexport interface LinearWorkspace {\n name: string;\n urlKey: string;\n}\n\nexport interface LinearIssue {\n id: string;\n projectId: string | null;\n /** Backend workspace identity when source ids span multiple workspaces. */\n workspaceId?: string;\n /** Raw Linear team id for exact team-source attribution. */\n teamId: string | null;\n /** Human key like `ENG-123`. */\n identifier: string;\n title: string;\n url: string;\n /** Workflow state name, e.g. `In Progress`. */\n state: string;\n /** Workflow state type, e.g. `backlog` / `unstarted` / `started` / `triage`. */\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Linear user who created the issue, when Linear returns one. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface LinearIssuePage {\n issues: LinearIssue[];\n /** Opaque cursor for the next page, or `null` on the last page. */\n nextCursor: string | null;\n}\n\nexport interface LinearProjectTeam {\n id: string;\n /** Short team key, e.g. `ENG`. */\n key: string;\n name: string;\n}\n\nexport interface LinearProject {\n id: string;\n name: string;\n /** Project state, e.g. `planned` / `started` / `paused` / `completed`. */\n state: string;\n /** Teams the project belongs to (the Settings picker groups by these). */\n teams: LinearProjectTeam[];\n}\n\n/** A Linear team, selectable as an intake source in its own right. */\nexport interface LinearTeam {\n id: string;\n /** Short team key, e.g. `ENG`. */\n key: string;\n name: string;\n /** Opaque intake source identifier. Optional on the wire for compatibility. */\n sourceId?: string;\n}\n\nexport interface LinearIssueComment {\n author: string | null;\n body: string;\n createdAt: string;\n}\n\n/** Full issue payload for agent context: everything in {@link LinearIssue} plus description and discussion. */\nexport interface LinearIssueDetail extends LinearIssue {\n /** Markdown body of the issue, or `null` when empty. */\n description: string | null;\n /** Discussion comments, oldest first. */\n comments: LinearIssueComment[];\n}\n\n/** The comment created by {@link LinearIntegration.createIssueComment}. */\nexport interface LinearCreatedComment {\n id: string;\n url: string;\n}\n\nconst LINEAR_ISSUES_PAGE_SIZE = 30;\nconst ISSUE_COMMENTS_PAGE_SIZE = 50;\nconst LINEAR_TEAMS_PAGE_SIZE = 100;\nconst LINEAR_TEAMS_MAX_PAGES = 20;\n/** Hard stop for comment pagination so a misbehaving cursor can't loop forever. */\nconst ISSUE_COMMENTS_MAX_PAGES = 20;\n\n/** Refresh this many ms before the recorded expiry to absorb clock skew. */\nconst TOKEN_REFRESH_SKEW_MS = 60_000;\n\n/** Re-check an org's Linear connection (and its scopes) at most this often. */\nconst CONNECTION_TTL_MS = 60_000;\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Thrown when the org's Linear authorization can no longer be renewed. */\nexport class LinearReauthRequiredError extends Error {\n constructor() {\n super('Linear authorization expired. Reconnect Linear to keep syncing intake issues.');\n }\n}\n\n/** Cached result of {@link LinearIntegration.checkConnection}. */\nexport interface LinearConnectionCheck {\n connected: boolean;\n /** Whether the granted OAuth scope allows posting issue comments. */\n canComment: boolean;\n checkedAt: number;\n}\n\ninterface IssuesQueryData {\n issues: {\n nodes: Array<{\n id: string;\n identifier: string;\n title: string;\n url: string;\n priorityLabel: string;\n createdAt: string;\n updatedAt: string;\n state: { name: string; type: string };\n project: { id: string } | null;\n assignee: { name: string } | null;\n creator: { name: string } | null;\n team: { id: string; key: string } | null;\n labels: { nodes: Array<{ name: string }> };\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n}\n\ninterface IssueCommentNode {\n body: string;\n createdAt: string;\n user: { name: string } | null;\n}\n\ninterface IssueCommentsPage {\n nodes: IssueCommentNode[];\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n}\n\ninterface IssueDetailQueryData {\n issue: {\n id: string;\n identifier: string;\n title: string;\n description: string | null;\n url: string;\n priorityLabel: string;\n createdAt: string;\n updatedAt: string;\n state: { name: string; type: string };\n project: { id: string } | null;\n assignee: { name: string } | null;\n creator: { name: string } | null;\n team: { id: string; key: string } | null;\n labels: { nodes: Array<{ name: string }> };\n comments: IssueCommentsPage;\n } | null;\n}\n\ninterface IssueCommentsQueryData {\n issue: { comments: IssueCommentsPage } | null;\n}\n\ninterface IssueIdQueryData {\n issue: { id: string } | null;\n}\n\ninterface CommentCreateMutationData {\n commentCreate: { success: boolean; comment: { id: string; url: string } | null };\n}\n\n/** POST a GraphQL query to Linear with the given OAuth access token. */\nasync function linearGraphql<T>(accessToken: string, query: string, variables?: Record<string, unknown>): Promise<T> {\n const res = await fetch(LINEAR_GRAPHQL_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(15_000),\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({ query, variables }),\n });\n if (!res.ok) {\n // Linear returns GraphQL errors (validation, missing scopes, …) with a\n // 400 status — surface the actual message instead of just the code.\n let detail: string | null = null;\n try {\n const errBody = (await res.json()) as { errors?: Array<{ message?: string }> };\n detail = errBody.errors?.[0]?.message ?? null;\n } catch {\n // Non-JSON error body; fall back to the status code alone.\n }\n const err = new Error(`Linear API request failed (${res.status})${detail ? `: ${detail}` : ''}`);\n (err as { status?: number }).status = res.status;\n throw err;\n }\n const body = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };\n if (body.errors?.length) {\n throw new Error(`Linear API error: ${body.errors[0]?.message ?? 'unknown error'}`);\n }\n if (!body.data) {\n throw new Error('Linear API returned no data.');\n }\n return body.data;\n}\n\nexport class LinearIntegration implements FactoryIntegration {\n /** Stable integration identifier (see `../base.ts`). */\n readonly id = 'linear';\n /** Bound once by the factory via `initialize()` before any surface is used. */\n #storage: LinearStorageHandle | undefined;\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n\n /** Bind Linear's slice of the generic integration storage, the projects domain, and the host auth seam. */\n initialize({\n storage,\n projects,\n auth,\n }: {\n storage: IntegrationStorageHandle;\n projects: FactoryProjectsStorage;\n auth: RouteAuth;\n }): void {\n this.#storage = storage as unknown as LinearStorageHandle;\n this.#projects = projects;\n this.#auth = auth;\n }\n\n get storage(): LinearStorageHandle {\n if (!this.#storage) {\n throw new Error('LinearIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#storage;\n }\n\n /** Factory projects domain — maps a session's resourceId to its owning org. */\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error('LinearIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#projects;\n }\n\n /**\n * Whether the host runs with web auth enabled. Linear connections are\n * org-owned, so every Linear surface is inert without a tenant auth seam.\n */\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n // ── Connection + OAuth token lifecycle ───────────────────────────────────\n\n /** Load the org's Linear connection, or `null` when not connected. */\n async loadConnection(orgId: string): Promise<LinearConnectionRow | null> {\n const connection = await this.storage.connections.get(orgId);\n if (!connection) return null;\n const { data } = connection;\n return {\n id: connection.id,\n orgId: connection.orgId,\n userId: connection.userId,\n accessToken: data.accessToken,\n scope: data.scope ?? null,\n refreshToken: data.refreshToken ?? null,\n expiresAt: data.expiresAtMs === null || data.expiresAtMs === undefined ? null : new Date(data.expiresAtMs),\n workspaceName: data.workspaceName ?? null,\n workspaceUrlKey: data.workspaceUrlKey ?? null,\n createdAt: connection.createdAt,\n updatedAt: connection.updatedAt,\n };\n }\n\n /** Insert or replace the org's connection (one per org). */\n async upsertConnection(input: UpsertLinearConnectionInput): Promise<void> {\n await this.storage.connections.upsert(input.orgId, {\n userId: input.userId,\n data: {\n accessToken: input.accessToken,\n refreshToken: input.refreshToken,\n expiresAtMs: input.expiresAt?.getTime() ?? null,\n scope: input.scope,\n workspaceName: input.workspaceName,\n workspaceUrlKey: input.workspaceUrlKey,\n },\n });\n // Let the agent tools see the new connection immediately.\n this.invalidateConnectionCache(input.orgId);\n }\n\n /** Persist a rotated token set on the org's existing connection row. */\n async #updateTokens(orgId: string, tokens: LinearTokenSet): Promise<void> {\n await this.storage.connections.update(orgId, data => ({\n ...data,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAtMs: tokens.expiresAt?.getTime() ?? null,\n // Refresh responses may omit scope; keep the recorded grant.\n scope: tokens.scope ?? data.scope,\n }));\n }\n\n /**\n * Whether the connection's token can post issue comments. Legacy rows\n * without a recorded scope were minted with `read` only, so they count as\n * read-only until the org reconnects Linear.\n */\n canPostComments(connection: LinearConnectionRow): boolean {\n const scopes = (connection.scope ?? '').split(/[\\s,]+/).filter(Boolean);\n return scopes.some(scope => scope === 'comments:create' || scope === 'write' || scope === 'admin');\n }\n\n /**\n * In-flight refreshes keyed by org. Linear rotates refresh tokens, so two\n * concurrent refreshes with the same token would invalidate each other —\n * single-flight ensures one exchange per org and shares the result.\n */\n readonly #inflightRefreshes = new Map<string, Promise<string>>();\n\n /**\n * Return a usable access token for the connection, proactively refreshing\n * it when the recorded expiry is past (or imminent). Throws\n * `LinearReauthRequiredError` when the token is expired and cannot be\n * refreshed — the org has to go through the OAuth flow again.\n */\n async getFreshAccessToken(connection: LinearConnectionRow): Promise<string> {\n const expired =\n connection.expiresAt !== null && connection.expiresAt.getTime() - TOKEN_REFRESH_SKEW_MS <= Date.now();\n if (!expired) return connection.accessToken;\n\n if (!connection.refreshToken) {\n // Legacy row from before refresh-token support: nothing to renew with.\n throw new LinearReauthRequiredError();\n }\n\n const existing = this.#inflightRefreshes.get(connection.orgId);\n if (existing) return existing;\n\n // The caller may hold a stale row: another request could have refreshed\n // and rotated the refresh token since this row was loaded. Reload before\n // refreshing so we don't burn the rotated token and force a false reauth.\n const latest = await this.loadConnection(connection.orgId);\n if (!latest) throw new LinearReauthRequiredError();\n\n const concurrent = this.#inflightRefreshes.get(connection.orgId);\n if (concurrent) return concurrent;\n\n const latestExpired = latest.expiresAt !== null && latest.expiresAt.getTime() - TOKEN_REFRESH_SKEW_MS <= Date.now();\n if (!latestExpired) return latest.accessToken;\n if (!latest.refreshToken) throw new LinearReauthRequiredError();\n\n const refreshToken = latest.refreshToken;\n const refresh = (async () => {\n try {\n const tokens = await this.refreshAccessToken(refreshToken);\n await this.#updateTokens(connection.orgId, tokens);\n return tokens.accessToken;\n } catch (err) {\n const status = (err as { status?: number }).status;\n // invalid_grant surfaces as 400/401: the refresh token was revoked or\n // already rotated away. Terminal for this connection.\n if (status === 400 || status === 401) throw new LinearReauthRequiredError();\n throw err;\n } finally {\n this.#inflightRefreshes.delete(connection.orgId);\n }\n })();\n this.#inflightRefreshes.set(connection.orgId, refresh);\n return refresh;\n }\n\n // ── Connection checks for agent tools ────────────────────────────────────\n\n /** Re-check an org's Linear connection (and its scopes) at most this often. */\n readonly #connectionChecks = new Map<string, LinearConnectionCheck>();\n\n /**\n * Whether the org has an active connection and whether its granted scope\n * allows posting comments. Cached per org with a short TTL — tool-set\n * resolution runs on every request.\n */\n async checkConnection(orgId: string): Promise<LinearConnectionCheck> {\n const cached = this.#connectionChecks.get(orgId);\n if (cached && Date.now() - cached.checkedAt < CONNECTION_TTL_MS) return cached;\n const connection = await this.loadConnection(orgId);\n const check: LinearConnectionCheck = {\n connected: connection !== null,\n canComment: connection !== null && this.canPostComments(connection),\n checkedAt: Date.now(),\n };\n this.#connectionChecks.set(orgId, check);\n return check;\n }\n\n /**\n * Drop the cached connection check for an org. Called after a connection is\n * persisted so the tools show up on the very next run instead of after the\n * TTL lapses.\n */\n invalidateConnectionCache(orgId: string): void {\n this.#connectionChecks.delete(orgId);\n }\n\n /**\n * A project's org never changes, so the resourceId → orgId mapping is\n * cached forever. `null` marks resource ids that aren't factory projects\n * (e.g. local default resources) so we don't re-query them on every\n * tool-set resolution.\n */\n readonly #orgIdByResourceId = new Map<string, string | null>();\n\n /** Map a session's resourceId to its owning org, or `null` when it isn't a project. */\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n // Non-UUID resource ids (local/dev resources) would make the uuid column\n // comparison throw — they're definitively \"not a project\", so cache that.\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n let orgId: string | null;\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n orgId = project?.orgId ?? null;\n } catch {\n // Transient database failure: skip the tools for this request but don't\n // cache the miss, so the next request retries the lookup.\n return null;\n }\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n }\n\n /** Test hook: clear the org/connection caches between specs. */\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n this.#connectionChecks.clear();\n }\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async ({ orgId }) => {\n const connection = await this.loadConnection(orgId);\n if (!connection) return [];\n const accessToken = await this.getFreshAccessToken(connection);\n const [projects, teams] = await Promise.all([this.listProjects(accessToken), this.listTeams(accessToken)]);\n return [\n ...projects.map(project => ({\n id: project.id,\n name: project.name,\n type: 'project' as const,\n })),\n ...teams.map(team => ({\n id: encodeSelfManagedTeamSourceId(team.id),\n name: team.name,\n type: 'team' as const,\n metadata: { teamKey: team.key },\n })),\n ];\n },\n listItems: async ({ orgId, sourceIds, attributionSourceIds, cursor }) => {\n if (sourceIds.length === 0) return { items: [], nextCursor: null };\n const connection = await this.loadConnection(orgId);\n if (!connection) return { items: [], nextCursor: null };\n const accessToken = await this.getFreshAccessToken(connection);\n const page = await this.#listIntakeIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds,\n attributionSourceIds,\n cursor,\n });\n return {\n items: page.issues.flatMap(issue => {\n if (!issue.sourceId) return [];\n return [\n {\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId: issue.sourceId,\n title: `${issue.identifier}: ${issue.title}`,\n status: issue.state ?? '',\n labels: issue.labels,\n assignee: issue.assignee,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: {\n identifier: issue.identifier,\n stateType: issue.stateType,\n priority: issue.priority,\n team: issue.source,\n },\n },\n ];\n }),\n nextCursor: page.nextCursor,\n };\n },\n listIssues: input => this.#listIntakeIssues(input),\n getIssue: input => this.#getIntakeIssue(input),\n createComment: input => this.#createIntakeComment(input),\n updateIssue: input => this.#updateIntakeIssue(input),\n };\n\n /**\n * Background-dispatch context: the org's OAuth connection with a fresh\n * token. Linear work items store the issue UUID directly as `externalId`.\n */\n async #resolveIntakeDispatch({\n orgId,\n externalSource,\n }: {\n orgId: string;\n externalSource: { type: string; externalId: string };\n }): Promise<{ connection: IntegrationConnection; issueId: string } | null> {\n if (externalSource.type !== 'issue') return null;\n const connection = await this.loadConnection(orgId);\n if (!connection) return null;\n const accessToken = await this.getFreshAccessToken(connection);\n return { connection: { type: 'oauth', accessToken }, issueId: externalSource.externalId };\n }\n /**\n * The OAuth connect/callback flow round-trips a signed `state` through\n * Linear, so a multi-replica deploy needs a deployment-stable state secret.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #clientId: string;\n readonly #clientSecret: string;\n\n readonly #rules: LinearEventRules;\n\n get rules(): LinearEventRules {\n return this.#rules;\n }\n\n constructor(config: LinearIntegrationConfig) {\n this.#rules = resolveLinearRules(config.rules);\n const missing = (['clientId', 'clientSecret'] as const).filter(key => !config[key]);\n if (missing.length > 0) {\n throw new Error(`LinearIntegration is missing required config: ${missing.join(', ')}.`);\n }\n this.#clientId = config.clientId;\n this.#clientSecret = config.clientSecret;\n }\n\n // ── OAuth ────────────────────────────────────────────────────────────────\n\n /**\n * Build the OAuth authorize URL. `prompt=consent` forces the workspace\n * picker even for an already-authorized user, so \"reconnect\" can switch\n * workspaces.\n */\n buildAuthorizeUrl(state: string, redirectUri: string): string {\n const url = new URL(LINEAR_AUTHORIZE_URL);\n url.searchParams.set('client_id', this.#clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('response_type', 'code');\n // `comments:create` lets the agent's linear_create_comment tool post\n // comments; everything else the integration does is read-only.\n url.searchParams.set('scope', 'read,comments:create');\n url.searchParams.set('state', state);\n url.searchParams.set('prompt', 'consent');\n return url.toString();\n }\n\n /** Exchange an OAuth `code` for a workspace-scoped token set. */\n async exchangeOAuthCode(code: string, redirectUri: string): Promise<LinearTokenSet> {\n return this.#requestTokens({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }, 'token exchange');\n }\n\n /**\n * Exchange a refresh token for a new token set. Linear rotates refresh\n * tokens, so the returned set replaces the stored one entirely. A 400/401\n * here means the refresh token is invalid/revoked and the org must\n * re-authorize.\n */\n async refreshAccessToken(refreshToken: string): Promise<LinearTokenSet> {\n return this.#requestTokens({ grant_type: 'refresh_token', refresh_token: refreshToken }, 'token refresh');\n }\n\n /** POST to Linear's token endpoint and normalize the response. */\n async #requestTokens(params: Record<string, string>, label: string): Promise<LinearTokenSet> {\n const res = await fetch(LINEAR_TOKEN_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(10_000),\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n ...params,\n client_id: this.#clientId,\n client_secret: this.#clientSecret,\n }),\n });\n if (!res.ok) {\n const err = new Error(`Linear ${label} failed (${res.status})`);\n (err as { status?: number }).status = res.status;\n throw err;\n }\n const body = (await res.json()) as {\n access_token?: string;\n refresh_token?: string;\n expires_in?: number;\n scope?: string;\n };\n if (!body.access_token) {\n throw new Error(`Linear ${label} returned no access token.`);\n }\n return {\n accessToken: body.access_token,\n refreshToken: body.refresh_token ?? null,\n expiresAt: typeof body.expires_in === 'number' ? new Date(Date.now() + body.expires_in * 1000) : null,\n scope: body.scope ?? null,\n };\n }\n\n // ── GraphQL reads/writes ─────────────────────────────────────────────────\n\n /** Fetch the workspace (organization) the access token is scoped to. */\n async fetchWorkspace(accessToken: string): Promise<LinearWorkspace> {\n const data = await linearGraphql<{ organization: { name: string; urlKey: string } }>(\n accessToken,\n `query { organization { name urlKey } }`,\n );\n return { name: data.organization.name, urlKey: data.organization.urlKey };\n }\n\n async #listIntakeIssues(input: ListIntakeIssuesInput): Promise<{ issues: IntakeIssue[]; nextCursor: string | null }> {\n const accessToken = getLinearAccessToken(input.connection);\n if (input.sourceIds.length === 0) return { issues: [], nextCursor: null };\n const attributionSourceIds = input.attributionSourceIds ?? input.sourceIds;\n const { projectIds, teamIds } = splitSelfManagedSourceIds(input.sourceIds);\n const cursors = decodeSelfManagedListCursor(input.cursor, input.sourceIds, attributionSourceIds);\n\n // Project-only intake still uses one Linear query, but its provider cursor\n // is wrapped so a later source-selection change cannot reinterpret it.\n if (teamIds.length === 0) {\n if (cursors.projects === null) return { issues: [], nextCursor: null };\n const result = await this.listActiveIssues(accessToken, cursors.projects, projectIds, input.labels);\n return {\n issues: result.issues.map(issue => linearIssueToIntakeIssue(issue)),\n nextCursor: encodeSelfManagedListCursor(\n { projects: result.nextCursor, teams: null },\n input.sourceIds,\n attributionSourceIds,\n ),\n };\n }\n\n // A team is selected. List projects and teams separately (the two Linear\n // filters would AND together in one query) and stamp each issue with the\n // selected source that surfaced it. Each source kind paginates on its own\n // cursor, carried in a compound cursor when both are present.\n const projectResult =\n projectIds.length > 0 && cursors.projects !== null\n ? await this.listActiveIssues(accessToken, cursors.projects, projectIds, input.labels)\n : { issues: [], nextCursor: null };\n const teamResult =\n cursors.teams !== null\n ? await this.listActiveIssues(accessToken, cursors.teams, undefined, input.labels, teamIds)\n : { issues: [], nextCursor: null };\n\n // Stamp project issues with their (selected) project id; stamp team issues\n // with the team source id. A team issue whose project was also selected is\n // reconciled by the dedupe step below (project wins).\n const projectIssues = projectResult.issues.map(issue => linearIssueToIntakeIssue(issue));\n const selectedTeamSourceById = new Map(teamIds.map(teamId => [teamId, encodeSelfManagedTeamSourceId(teamId)]));\n const selectedProjectIds = new Set(splitSelfManagedSourceIds(attributionSourceIds).projectIds);\n const teamIssues = teamResult.issues\n .filter(issue => issue.projectId === null || !selectedProjectIds.has(issue.projectId))\n .map(issue => {\n const teamSourceId = issue.teamId ? selectedTeamSourceById.get(issue.teamId) : undefined;\n if (!teamSourceId) throw new Error('Linear returned an issue outside the selected teams.');\n return { ...linearIssueToIntakeIssue(issue), sourceId: teamSourceId };\n });\n\n const deduped = dedupeSelfManagedIssues([...projectIssues, ...teamIssues]);\n return {\n issues: deduped,\n nextCursor: encodeSelfManagedListCursor(\n { projects: projectResult.nextCursor, teams: teamResult.nextCursor },\n input.sourceIds,\n attributionSourceIds,\n ),\n };\n }\n\n async #getIntakeIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n const accessToken = getLinearAccessToken(input.connection);\n const issue = await this.fetchIssueDetail(accessToken, input.issueId);\n if (!issue) return null;\n return {\n ...linearIssueToIntakeIssue(issue),\n description: issue.description,\n commentCount: issue.comments.length,\n comments: issue.comments,\n };\n }\n\n async #createIntakeComment(input: CreateIntakeCommentInput): Promise<{ id: string; url: string } | null> {\n const accessToken = getLinearAccessToken(input.connection);\n return this.createIssueComment(accessToken, input.issueId, input.body);\n }\n\n async #updateIntakeIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n const accessToken = getLinearAccessToken(input.connection);\n const issue = await this.fetchIssueDetail(accessToken, input.issueId);\n if (!issue) return null;\n const teamKey = issue.team;\n if (!teamKey) return null;\n const states = await this.#listTeamWorkflowStates(accessToken, teamKey);\n let targetState: { id: string; name: string; type: string } | null = null;\n if (input.state.kind === 'byType') {\n const wantedType = input.state.stateType;\n targetState = states.find(state => state.type === wantedType) ?? null;\n } else {\n const wanted = input.state.name.toLowerCase();\n targetState = states.find(state => state.name.toLowerCase() === wanted) ?? null;\n }\n if (!targetState) return null;\n if (targetState.name === issue.state) {\n return linearIssueToIntakeIssue(issue);\n }\n const data = await linearGraphql<{ issueUpdate: { success: boolean } }>(\n accessToken,\n `mutation UpdateIssueState($id: String!, $stateId: String!) {\n issueUpdate(id: $id, input: { stateId: $stateId }) { success }\n }`,\n { id: issue.id, stateId: targetState.id },\n );\n if (!data.issueUpdate.success) {\n throw new Error('Linear did not accept the issue update.');\n }\n const fresh = await this.fetchIssueDetail(accessToken, issue.id);\n if (!fresh) return null;\n return linearIssueToIntakeIssue(fresh);\n }\n\n async #listTeamWorkflowStates(\n accessToken: string,\n teamKey: string,\n ): Promise<Array<{ id: string; name: string; type: string }>> {\n const data = await linearGraphql<{\n team: { states: { nodes: Array<{ id: string; name: string; type: string }> } } | null;\n }>(\n accessToken,\n `query TeamStates($key: String!) {\n team(id: $key) { states(first: 100) { nodes { id name type } } }\n }`,\n { key: teamKey },\n );\n return data.team?.states.nodes ?? [];\n }\n\n /** List the workspace's projects (for the Settings intake-source picker). */\n async listProjects(accessToken: string): Promise<LinearProject[]> {\n const data = await linearGraphql<{\n projects: {\n nodes: Array<{\n id: string;\n name: string;\n state: string;\n teams: { nodes: Array<{ id: string; key: string; name: string }> };\n }>;\n };\n }>(\n accessToken,\n `query { projects(first: 100) { nodes { id name state teams(first: 10) { nodes { id key name } } } } }`,\n );\n return data.projects.nodes.map(node => ({\n id: node.id,\n name: node.name,\n state: node.state,\n teams: node.teams.nodes.map(team => ({ id: team.id, key: team.key, name: team.name })),\n }));\n }\n\n /** List the workspace's teams (for the Settings intake-source picker). */\n async listTeams(accessToken: string): Promise<LinearTeam[]> {\n const teams: Array<{ id: string; key: string; name: string }> = [];\n let after: string | undefined;\n for (let page = 0; page < LINEAR_TEAMS_MAX_PAGES; page += 1) {\n const data = await linearGraphql<{\n teams: {\n nodes: Array<{ id: string; key: string; name: string }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n }>(\n accessToken,\n `query Teams($first: Int!, $after: String) {\n teams(first: $first, after: $after) {\n nodes { id key name }\n pageInfo { hasNextPage endCursor }\n }\n }`,\n { first: LINEAR_TEAMS_PAGE_SIZE, ...(after ? { after } : {}) },\n );\n teams.push(...data.teams.nodes);\n if (!data.teams.pageInfo.hasNextPage || !data.teams.pageInfo.endCursor) break;\n // A page that hands back the cursor it was asked for would replay forever.\n if (data.teams.pageInfo.endCursor === after) throw invalidLinearCursor();\n after = data.teams.pageInfo.endCursor;\n }\n return teams.map(team => ({\n id: team.id,\n key: team.key,\n name: team.name,\n sourceId: encodeSelfManagedTeamSourceId(team.id),\n }));\n }\n\n sourceMatchesIssue(sourceId: string, issue: Pick<LinearIssueDetail, 'projectId' | 'teamId'>): boolean {\n return isSelfManagedTeamSourceId(sourceId)\n ? issue.teamId === decodeSelfManagedTeamSourceId(sourceId)\n : issue.projectId === sourceId;\n }\n\n /**\n * List one page of the workspace's active issues (triage/backlog/unstarted/\n * started — completed and canceled are excluded), most recently updated\n * first. When `projectIds` is provided, only issues from those projects are\n * returned. When `teamIds` is provided, only issues in those teams are\n * returned, including issues that belong to no project. Callers list team\n * sources and project sources in separate calls so the two filters are not\n * AND-ed together.\n */\n async listActiveIssues(\n accessToken: string,\n after?: string,\n projectIds?: string[],\n labels?: string[],\n teamIds?: string[],\n ): Promise<LinearIssuePage> {\n const normalizedLabels = [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n const projectFilter = projectIds?.length ? ', project: { id: { in: $projectIds } }' : '';\n const projectVar = projectIds?.length ? ', $projectIds: [ID!]' : '';\n const teamFilter = teamIds?.length ? ', team: { id: { in: $teamIds } }' : '';\n const teamVar = teamIds?.length ? ', $teamIds: [ID!]' : '';\n const labelFilter = normalizedLabels.length > 0 ? ', labels: { name: { in: $labels } }' : '';\n const labelVar = normalizedLabels.length > 0 ? ', $labels: [String!]' : '';\n const data = await linearGraphql<IssuesQueryData>(\n accessToken,\n `query Intake($first: Int!, $after: String${projectVar}${teamVar}${labelVar}) {\n issues(\n first: $first\n after: $after\n orderBy: updatedAt\n filter: { state: { type: { in: [\"triage\", \"backlog\", \"unstarted\", \"started\"] } }${projectFilter}${teamFilter}${labelFilter} }\n ) {\n nodes {\n id\n identifier\n title\n url\n priorityLabel\n createdAt\n updatedAt\n state { name type }\n project { id }\n assignee { name }\n creator { name }\n team { id key }\n labels { nodes { name } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }`,\n {\n first: LINEAR_ISSUES_PAGE_SIZE,\n after: after ?? null,\n ...(projectIds?.length ? { projectIds } : {}),\n ...(teamIds?.length ? { teamIds } : {}),\n ...(normalizedLabels.length > 0 ? { labels: normalizedLabels } : {}),\n },\n );\n const { nodes, pageInfo } = data.issues;\n return {\n issues: nodes.map(node => ({\n id: node.id,\n projectId: node.project?.id ?? null,\n identifier: node.identifier,\n title: node.title,\n url: node.url,\n state: node.state.name,\n stateType: node.state.type,\n priorityLabel: node.priorityLabel,\n assignee: node.assignee?.name ?? null,\n creator: node.creator?.name ?? null,\n team: node.team?.key ?? null,\n labels: node.labels.nodes.map(label => label.name),\n createdAt: node.createdAt,\n updatedAt: node.updatedAt,\n teamId: node.team?.id ?? null,\n })),\n nextCursor: pageInfo.hasNextPage ? pageInfo.endCursor : null,\n };\n }\n\n /** Follow `comments.pageInfo` until exhausted so long discussions aren't truncated. */\n async #fetchRemainingIssueComments(\n accessToken: string,\n issueId: string,\n firstPage: IssueCommentsPage,\n ): Promise<IssueCommentNode[]> {\n const nodes = [...firstPage.nodes];\n let { hasNextPage, endCursor } = firstPage.pageInfo;\n for (let page = 1; hasNextPage && endCursor && page < ISSUE_COMMENTS_MAX_PAGES; page++) {\n const data = await linearGraphql<IssueCommentsQueryData>(\n accessToken,\n `query IssueComments($id: String!, $first: Int!, $after: String!) {\n issue(id: $id) {\n comments(first: $first, after: $after) {\n nodes { body createdAt user { name } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }`,\n { id: issueId, first: ISSUE_COMMENTS_PAGE_SIZE, after: endCursor },\n );\n const comments = data.issue?.comments;\n if (!comments) break;\n nodes.push(...comments.nodes);\n if (comments.pageInfo.hasNextPage && comments.pageInfo.endCursor === endCursor) throw invalidLinearCursor();\n ({ hasNextPage, endCursor } = comments.pageInfo);\n }\n return nodes;\n }\n\n /**\n * Fetch one issue with its description and comments. `idOrIdentifier`\n * accepts both the Linear UUID and the human key (`ENG-123`). Returns\n * `null` when the issue doesn't exist (Linear reports it as an \"Entity not\n * found\" error).\n */\n async fetchIssueDetail(\n accessToken: string,\n idOrIdentifier: string,\n _sourceIds?: string[],\n _routedSourceIds?: string[],\n ): Promise<LinearIssueDetail | null> {\n let data: IssueDetailQueryData;\n try {\n data = await linearGraphql<IssueDetailQueryData>(\n accessToken,\n `query IssueDetail($id: String!, $commentsFirst: Int!) {\n issue(id: $id) {\n id\n identifier\n title\n description\n url\n priorityLabel\n createdAt\n updatedAt\n state { name type }\n project { id }\n assignee { name }\n creator { name }\n team { id key }\n labels { nodes { name } }\n comments(first: $commentsFirst) {\n nodes { body createdAt user { name } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }`,\n { id: idOrIdentifier, commentsFirst: ISSUE_COMMENTS_PAGE_SIZE },\n );\n } catch (err) {\n // Linear surfaces unknown ids/identifiers as a GraphQL \"Entity not\n // found\" error rather than a null node — map that to \"issue doesn't\n // exist\".\n if (err instanceof Error && /entity not found/i.test(err.message)) return null;\n throw err;\n }\n const issue = data.issue;\n if (!issue) return null;\n const allComments = await this.#fetchRemainingIssueComments(accessToken, issue.id, issue.comments);\n const comments = allComments.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n return {\n id: issue.id,\n projectId: issue.project?.id ?? null,\n teamId: issue.team?.id ?? null,\n identifier: issue.identifier,\n title: issue.title,\n description: issue.description?.trim() ? issue.description : null,\n url: issue.url,\n state: issue.state.name,\n stateType: issue.state.type,\n priorityLabel: issue.priorityLabel,\n assignee: issue.assignee?.name ?? null,\n creator: issue.creator?.name ?? null,\n team: issue.team?.key ?? null,\n labels: issue.labels.nodes.map(label => label.name),\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n comments: comments.map(comment => ({\n author: comment.user?.name ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n }\n\n /**\n * Post a comment on an issue. `idOrIdentifier` accepts both the Linear UUID\n * and the human key (`ENG-123`) — the identifier is resolved to a UUID\n * first because `commentCreate` only accepts UUIDs. Returns `null` when the\n * issue doesn't exist.\n */\n async createIssueComment(\n accessToken: string,\n idOrIdentifier: string,\n body: string,\n ): Promise<LinearCreatedComment | null> {\n let issueId: string;\n try {\n const data = await linearGraphql<IssueIdQueryData>(\n accessToken,\n `query IssueId($id: String!) { issue(id: $id) { id } }`,\n { id: idOrIdentifier },\n );\n if (!data.issue) return null;\n issueId = data.issue.id;\n } catch (err) {\n if (err instanceof Error && /entity not found/i.test(err.message)) return null;\n throw err;\n }\n const data = await linearGraphql<CommentCreateMutationData>(\n accessToken,\n `mutation CommentCreate($input: CommentCreateInput!) {\n commentCreate(input: $input) { success comment { id url } }\n }`,\n { input: { issueId, body } },\n );\n if (!data.commentCreate.success || !data.commentCreate.comment) {\n throw new Error('Linear did not accept the comment.');\n }\n return data.commentCreate.comment;\n }\n\n // ── FactoryIntegration surface ───────────────────────────────────────────\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (!linearIssueReconciliationEnabled()) return [];\n const reconcile = attachLinearIssueReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = linearIssueReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * The integration's HTTP surface: `/web/linear/*` + `/auth/linear/*` Mastra\n * `apiRoutes` (status, OAuth connect/callback, projects + issues for\n * Intake). Handlers operate on this instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n return buildLinearRoutes({\n linear: this,\n auth: ctx.auth,\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n intake: ctx.storage.intake,\n projects: ctx.storage.projects,\n ingestFactoryIssues: attachLinearRules(this, ctx),\n workItems: ctx.runtime?.workItems,\n boards: ctx.runtime?.boards,\n });\n }\n\n /**\n * Org-scoped agent tools: issue detail + comment tools for sessions whose\n * project belongs to an org with an active Linear connection.\n */\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildLinearAgentTools({ requestContext: args.requestContext, linear: this });\n }\n\n /** Non-secret config snapshot for system diagnostics/startup logs. */\n diagnostics(): Record<string, unknown> {\n return {\n oauthAppConfigured: true,\n };\n }\n}\n\nfunction getLinearAccessToken(connection: IntegrationConnection): string {\n if (connection.type !== 'oauth') {\n throw new Error('Linear capabilities require an OAuth connection.');\n }\n return connection.accessToken;\n}\n\n/**\n * Self-managed source ids. Projects use their raw Linear project id (no prefix,\n * preserving existing intake bindings). Teams are prefixed so the two never\n * collide and callers can tell them apart.\n */\nconst SELF_MANAGED_TEAM_SOURCE_PREFIX = 'linear-team:';\n\nfunction encodeSelfManagedTeamSourceId(teamId: string): string {\n return `${SELF_MANAGED_TEAM_SOURCE_PREFIX}${teamId}`;\n}\n\nfunction isSelfManagedTeamSourceId(sourceId: string): boolean {\n return sourceId.startsWith(SELF_MANAGED_TEAM_SOURCE_PREFIX);\n}\n\nfunction decodeSelfManagedTeamSourceId(sourceId: string): string {\n return sourceId.slice(SELF_MANAGED_TEAM_SOURCE_PREFIX.length);\n}\n\n/**\n * Split selected source ids into raw project ids and raw team ids. A team\n * source id carries the `linear-team:` prefix; everything else is a project id.\n */\nfunction splitSelfManagedSourceIds(sourceIds: string[]): { projectIds: string[]; teamIds: string[] } {\n const projectIds: string[] = [];\n const teamIds: string[] = [];\n for (const sourceId of sourceIds) {\n if (isSelfManagedTeamSourceId(sourceId)) teamIds.push(decodeSelfManagedTeamSourceId(sourceId));\n else projectIds.push(sourceId);\n }\n return { projectIds, teamIds };\n}\n\ntype SelfManagedListCursor = {\n v: 1;\n sourceSet: string;\n projects: string | null;\n teams: string | null;\n};\n\nfunction linearSourceSetFingerprint(sourceIds: string[], attributionSourceIds: string[]): string {\n const scope = {\n sourceIds: [...new Set(sourceIds)].sort(),\n attributionSourceIds: [...new Set(attributionSourceIds)].sort(),\n };\n return createHash('sha256').update(JSON.stringify(scope)).digest('base64url');\n}\n\nfunction invalidLinearCursor(): Error {\n return Object.assign(new Error('Linear cursor is invalid or stale.'), { code: 'invalid_cursor' as const });\n}\n\nfunction isCursorValue(value: unknown): value is string | null {\n return value === null || typeof value === 'string';\n}\n\nfunction decodeSelfManagedListCursor(\n cursor: string | undefined,\n sourceIds: string[],\n attributionSourceIds: string[],\n): { projects: string | null | undefined; teams: string | null | undefined } {\n const { projectIds, teamIds } = splitSelfManagedSourceIds(sourceIds);\n if (!cursor) {\n return {\n projects: projectIds.length > 0 ? undefined : null,\n teams: teamIds.length > 0 ? undefined : null,\n };\n }\n try {\n const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<SelfManagedListCursor>;\n if (\n parsed.v !== 1 ||\n parsed.sourceSet !== linearSourceSetFingerprint(sourceIds, attributionSourceIds) ||\n !isCursorValue(parsed.projects) ||\n !isCursorValue(parsed.teams)\n ) {\n throw invalidLinearCursor();\n }\n return {\n projects: parsed.projects,\n teams: parsed.teams,\n };\n } catch {\n throw invalidLinearCursor();\n }\n}\n\nfunction encodeSelfManagedListCursor(\n state: Pick<SelfManagedListCursor, 'projects' | 'teams'>,\n sourceIds: string[],\n attributionSourceIds: string[],\n): string | null {\n if (state.projects === null && state.teams === null) return null;\n return Buffer.from(\n JSON.stringify({\n v: 1,\n sourceSet: linearSourceSetFingerprint(sourceIds, attributionSourceIds),\n ...state,\n } satisfies SelfManagedListCursor),\n ).toString('base64url');\n}\n\n/**\n * Deduplicate issues that surfaced from both a selected team and one of its\n * selected projects. Keeps one entry per Linear issue UUID.\n *\n * Tie-breaker — MOST-SPECIFIC-WINS: an issue in a selected project is\n * attributed to that project source (routes to the project's board); the team\n * source covers only the remainder (projectless issues and issues in projects\n * that were not separately selected). Change the comparison here to change the\n * routing policy — this is the single precedence point for the self-managed\n * integration, mirroring the platform-backed one.\n */\nfunction dedupeSelfManagedIssues(\n issues: Array<IntakeIssue & { sourceId?: string | null }>,\n): Array<IntakeIssue & { sourceId?: string | null }> {\n const isProjectSource = (sourceId: string | null | undefined): boolean =>\n typeof sourceId === 'string' && sourceId.length > 0 && !isSelfManagedTeamSourceId(sourceId);\n const winners = new Map<string, IntakeIssue & { sourceId?: string | null }>();\n for (const issue of issues) {\n const existing = winners.get(issue.id);\n if (!existing) {\n winners.set(issue.id, issue);\n continue;\n }\n // Project source beats team source; otherwise keep the first seen.\n if (isProjectSource(issue.sourceId) && !isProjectSource(existing.sourceId)) {\n winners.set(issue.id, issue);\n }\n }\n const seen = new Set<string>();\n const ordered: Array<IntakeIssue & { sourceId?: string | null }> = [];\n for (const issue of issues) {\n if (seen.has(issue.id)) continue;\n seen.add(issue.id);\n ordered.push(winners.get(issue.id)!);\n }\n return ordered;\n}\n\nfunction linearIssueToIntakeIssue(issue: Omit<LinearIssue, 'projectId'> & { projectId?: string | null }): IntakeIssue {\n return {\n id: issue.id,\n sourceId: issue.projectId ?? null,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.creator,\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priorityLabel,\n assignee: issue.assignee,\n source: issue.team,\n labels: issue.labels,\n commentCount: null,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AA6G7B,MAAM,0BAA0B;AAChC,MAAM,2BAA2B;AACjC,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;;AAE/B,MAAM,2BAA2B;;AAGjC,MAAM,wBAAwB;;AAG9B,MAAM,oBAAoB;AAE1B,MAAM,eAAe;;AAGrB,IAAa,4BAAb,cAA+C,MAAM;CACnD,cAAc;EACZ,MAAM,+EAA+E;CACvF;AACF;;AA2EA,eAAe,cAAiB,aAAqB,OAAe,WAAiD;CACnH,MAAM,MAAM,MAAM,MAAM,oBAAoB;EAC1C,QAAQ;EACR,QAAQ,YAAY,QAAQ,IAAM;EAClC,SAAS;GACP,gBAAgB;GAChB,eAAe,UAAU;EAC3B;EACA,MAAM,KAAK,UAAU;GAAE;GAAO;EAAU,CAAC;CAC3C,CAAC;CACD,IAAI,CAAC,IAAI,IAAI;EAGX,IAAI,SAAwB;EAC5B,IAAI;GAEF,UAAS,MADc,IAAI,KAAK,EAAA,CACf,SAAS,EAAE,EAAE,WAAW;EAC3C,QAAQ,CAER;EACA,MAAM,sBAA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ecks","#orgIdByResourceId","#resolveIntakeDispatch","#listIntakeIssues","#getIntakeIssue","#createIntakeComment","#updateIntakeIssue","#clientId","#clientSecret","#rules","#requestTokens","#listTeamWorkflowStates","#fetchRemainingIssueComments"],"sources":["../../../src/integrations/linear/integration.ts"],"sourcesContent":["/**\n * `LinearIntegration` — the self-contained Linear integration.\n *\n * Implements the system-wide `FactoryIntegration` contract\n * (`../factory-integration.ts`): the deploy entry reads the Linear OAuth env\n * vars ONCE, constructs an instance with explicit credentials, and passes it\n * to `MastraFactory`. Everything Linear-flavored the system does — the OAuth\n * connect/callback flow, workspace/project/issue reads for Intake, and the\n * agent's issue tools — flows through this instance. No other module reads\n * `LINEAR_*` env vars.\n *\n * The class owns:\n * - OAuth: the user-facing authorize URL, code exchange, and refresh-token\n * rotation against Linear's `/oauth/token` endpoint.\n * - GraphQL reads/writes: viewer workspace, projects, active issues for\n * Intake, full issue detail (description + discussion), issue comments.\n * - The HTTP surface (`routes()`) and per-request agent tools\n * (`agentTools()`), delegating to `./routes.ts` / `./agent-tools.ts` with\n * `this` as the API client.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\nimport type { IntegrationConnection } from '../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n ListIntakeIssuesInput,\n UpdateIntakeIssueInput,\n} from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntegrationStorageHandle } from '../../storage/domains/integrations/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { buildLinearAgentTools } from './agent-tools.js';\nimport type { LinearEventRules, LinearRuleOverrides } from './default-rules.js';\nimport { resolveLinearRules } from './default-rules.js';\nimport { attachLinearIssueReconciler } from './issue-reconciler.js';\nimport { linearIssueReconciliationEnabled, linearIssueReconciliationInterval } from './reconciliation-config.js';\nimport { buildLinearRoutes } from './routes.js';\nimport { attachLinearRules } from './rules.js';\nimport type { LinearConnectionRow, LinearStorageHandle, UpsertLinearConnectionInput } from './storage.js';\n\nconst LINEAR_GRAPHQL_URL = 'https://api.linear.app/graphql';\nconst LINEAR_TOKEN_URL = 'https://api.linear.app/oauth/token';\nconst LINEAR_AUTHORIZE_URL = 'https://linear.app/oauth/authorize';\n\n/** Credentials and optional event rules for the Linear OAuth application. */\nexport interface LinearIntegrationConfig {\n /** Per-event replacements; omitted events retain defaults, null disables. */\n rules?: LinearRuleOverrides;\n /** OAuth client id of the Linear application. */\n clientId: string;\n /** OAuth client secret of the Linear application. */\n clientSecret: string;\n}\n\n/**\n * Tokens minted by Linear's `/oauth/token` endpoint. Linear access tokens\n * expire (24h) and refresh tokens rotate: every refresh invalidates the old\n * pair, so callers must persist the whole set after each exchange.\n */\nexport interface LinearTokenSet {\n accessToken: string;\n /** Null when Linear issued no refresh token (legacy non-expiring apps). */\n refreshToken: string | null;\n /** Null when Linear reported no `expires_in`. */\n expiresAt: Date | null;\n /** Scopes granted to the token as reported by Linear; null when omitted. */\n scope: string | null;\n}\n\nexport interface LinearWorkspace {\n name: string;\n urlKey: string;\n}\n\nexport interface LinearIssue {\n id: string;\n projectId: string | null;\n /** Backend workspace identity when source ids span multiple workspaces. */\n workspaceId?: string;\n /** Raw Linear team id for exact team-source attribution. */\n teamId: string | null;\n /** Human key like `ENG-123`. */\n identifier: string;\n title: string;\n url: string;\n /** Workflow state name, e.g. `In Progress`. */\n state: string;\n /** Workflow state type, e.g. `backlog` / `unstarted` / `started` / `triage`. */\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Linear user who created the issue, when Linear returns one. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface LinearIssuePage {\n issues: LinearIssue[];\n /** Opaque cursor for the next page, or `null` on the last page. */\n nextCursor: string | null;\n}\n\nexport interface LinearProjectTeam {\n id: string;\n /** Short team key, e.g. `ENG`. */\n key: string;\n name: string;\n}\n\nexport interface LinearProject {\n id: string;\n name: string;\n /** Project state, e.g. `planned` / `started` / `paused` / `completed`. */\n state: string;\n /** Teams the project belongs to (the Settings picker groups by these). */\n teams: LinearProjectTeam[];\n}\n\n/** A Linear team, selectable as an intake source in its own right. */\nexport interface LinearTeam {\n id: string;\n /** Short team key, e.g. `ENG`. */\n key: string;\n name: string;\n /** Opaque intake source identifier. Optional on the wire for compatibility. */\n sourceId?: string;\n}\n\nexport interface LinearIssueComment {\n author: string | null;\n body: string;\n createdAt: string;\n}\n\n/** Full issue payload for agent context: everything in {@link LinearIssue} plus description and discussion. */\nexport interface LinearIssueDetail extends LinearIssue {\n /** Markdown body of the issue, or `null` when empty. */\n description: string | null;\n /** Discussion comments, oldest first. */\n comments: LinearIssueComment[];\n}\n\n/** The comment created by {@link LinearIntegration.createIssueComment}. */\nexport interface LinearCreatedComment {\n id: string;\n url: string;\n}\n\nconst LINEAR_ISSUES_PAGE_SIZE = 30;\nconst ISSUE_COMMENTS_PAGE_SIZE = 50;\nconst LINEAR_TEAMS_PAGE_SIZE = 100;\nconst LINEAR_TEAMS_MAX_PAGES = 20;\n/** Hard stop for comment pagination so a misbehaving cursor can't loop forever. */\nconst ISSUE_COMMENTS_MAX_PAGES = 20;\n\n/** Refresh this many ms before the recorded expiry to absorb clock skew. */\nconst TOKEN_REFRESH_SKEW_MS = 60_000;\n\n/** Re-check an org's Linear connection (and its scopes) at most this often. */\nconst CONNECTION_TTL_MS = 60_000;\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Thrown when the org's Linear authorization can no longer be renewed. */\nexport class LinearReauthRequiredError extends Error {\n constructor() {\n super('Linear authorization expired. Reconnect Linear to keep syncing intake issues.');\n }\n}\n\n/** Cached result of {@link LinearIntegration.checkConnection}. */\nexport interface LinearConnectionCheck {\n connected: boolean;\n /** Whether the granted OAuth scope allows posting issue comments. */\n canComment: boolean;\n checkedAt: number;\n}\n\ninterface IssuesQueryData {\n issues: {\n nodes: Array<{\n id: string;\n identifier: string;\n title: string;\n url: string;\n priorityLabel: string;\n createdAt: string;\n updatedAt: string;\n state: { name: string; type: string };\n project: { id: string } | null;\n assignee: { name: string } | null;\n creator: { name: string } | null;\n team: { id: string; key: string } | null;\n labels: { nodes: Array<{ name: string }> };\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n}\n\ninterface IssueCommentNode {\n body: string;\n createdAt: string;\n user: { name: string } | null;\n}\n\ninterface IssueCommentsPage {\n nodes: IssueCommentNode[];\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n}\n\ninterface IssueDetailQueryData {\n issue: {\n id: string;\n identifier: string;\n title: string;\n description: string | null;\n url: string;\n priorityLabel: string;\n createdAt: string;\n updatedAt: string;\n state: { name: string; type: string };\n project: { id: string } | null;\n assignee: { name: string } | null;\n creator: { name: string } | null;\n team: { id: string; key: string } | null;\n labels: { nodes: Array<{ name: string }> };\n comments: IssueCommentsPage;\n } | null;\n}\n\ninterface IssueCommentsQueryData {\n issue: { comments: IssueCommentsPage } | null;\n}\n\ninterface IssueIdQueryData {\n issue: { id: string } | null;\n}\n\ninterface CommentCreateMutationData {\n commentCreate: { success: boolean; comment: { id: string; url: string } | null };\n}\n\n/** POST a GraphQL query to Linear with the given OAuth access token. */\nasync function linearGraphql<T>(accessToken: string, query: string, variables?: Record<string, unknown>): Promise<T> {\n const res = await fetch(LINEAR_GRAPHQL_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(15_000),\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({ query, variables }),\n });\n if (!res.ok) {\n // Linear returns GraphQL errors (validation, missing scopes, …) with a\n // 400 status — surface the actual message instead of just the code.\n let detail: string | null = null;\n try {\n const errBody = (await res.json()) as { errors?: Array<{ message?: string }> };\n detail = errBody.errors?.[0]?.message ?? null;\n } catch {\n // Non-JSON error body; fall back to the status code alone.\n }\n const err = new Error(`Linear API request failed (${res.status})${detail ? `: ${detail}` : ''}`);\n (err as { status?: number }).status = res.status;\n throw err;\n }\n const body = (await res.json()) as { data?: T; errors?: Array<{ message?: string }> };\n if (body.errors?.length) {\n throw new Error(`Linear API error: ${body.errors[0]?.message ?? 'unknown error'}`);\n }\n if (!body.data) {\n throw new Error('Linear API returned no data.');\n }\n return body.data;\n}\n\nexport class LinearIntegration implements FactoryIntegration {\n /** Stable integration identifier (see `../base.ts`). */\n readonly id = 'linear';\n /** Bound once by the factory via `initialize()` before any surface is used. */\n #storage: LinearStorageHandle | undefined;\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n\n /** Bind Linear's slice of the generic integration storage, the projects domain, and the host auth seam. */\n initialize({\n storage,\n projects,\n auth,\n }: {\n storage: IntegrationStorageHandle;\n projects: FactoryProjectsStorage;\n auth: RouteAuth;\n }): void {\n this.#storage = storage as unknown as LinearStorageHandle;\n this.#projects = projects;\n this.#auth = auth;\n }\n\n get storage(): LinearStorageHandle {\n if (!this.#storage) {\n throw new Error('LinearIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#storage;\n }\n\n /** Factory projects domain — maps a session's resourceId to its owning org. */\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error('LinearIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#projects;\n }\n\n /**\n * Whether the host runs with web auth enabled. Linear connections are\n * org-owned, so every Linear surface is inert without a tenant auth seam.\n */\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n // ── Connection + OAuth token lifecycle ───────────────────────────────────\n\n /** Load the org's Linear connection, or `null` when not connected. */\n async loadConnection(orgId: string): Promise<LinearConnectionRow | null> {\n const connection = await this.storage.connections.get(orgId);\n if (!connection) return null;\n const { data } = connection;\n return {\n id: connection.id,\n orgId: connection.orgId,\n userId: connection.userId,\n accessToken: data.accessToken,\n scope: data.scope ?? null,\n refreshToken: data.refreshToken ?? null,\n expiresAt: data.expiresAtMs === null || data.expiresAtMs === undefined ? null : new Date(data.expiresAtMs),\n workspaceName: data.workspaceName ?? null,\n workspaceUrlKey: data.workspaceUrlKey ?? null,\n createdAt: connection.createdAt,\n updatedAt: connection.updatedAt,\n };\n }\n\n /** Insert or replace the org's connection (one per org). */\n async upsertConnection(input: UpsertLinearConnectionInput): Promise<void> {\n await this.storage.connections.upsert(input.orgId, {\n userId: input.userId,\n data: {\n accessToken: input.accessToken,\n refreshToken: input.refreshToken,\n expiresAtMs: input.expiresAt?.getTime() ?? null,\n scope: input.scope,\n workspaceName: input.workspaceName,\n workspaceUrlKey: input.workspaceUrlKey,\n },\n });\n // Let the agent tools see the new connection immediately.\n this.invalidateConnectionCache(input.orgId);\n }\n\n /** Persist a rotated token set on the org's existing connection row. */\n async #updateTokens(orgId: string, tokens: LinearTokenSet): Promise<void> {\n await this.storage.connections.update(orgId, data => ({\n ...data,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAtMs: tokens.expiresAt?.getTime() ?? null,\n // Refresh responses may omit scope; keep the recorded grant.\n scope: tokens.scope ?? data.scope,\n }));\n }\n\n /**\n * Whether the connection's token can post issue comments. Legacy rows\n * without a recorded scope were minted with `read` only, so they count as\n * read-only until the org reconnects Linear.\n */\n canPostComments(connection: LinearConnectionRow): boolean {\n const scopes = (connection.scope ?? '').split(/[\\s,]+/).filter(Boolean);\n return scopes.some(scope => scope === 'comments:create' || scope === 'write' || scope === 'admin');\n }\n\n /**\n * In-flight refreshes keyed by org. Linear rotates refresh tokens, so two\n * concurrent refreshes with the same token would invalidate each other —\n * single-flight ensures one exchange per org and shares the result.\n */\n readonly #inflightRefreshes = new Map<string, Promise<string>>();\n\n /**\n * Return a usable access token for the connection, proactively refreshing\n * it when the recorded expiry is past (or imminent). Throws\n * `LinearReauthRequiredError` when the token is expired and cannot be\n * refreshed — the org has to go through the OAuth flow again.\n */\n async getFreshAccessToken(connection: LinearConnectionRow): Promise<string> {\n const expired =\n connection.expiresAt !== null && connection.expiresAt.getTime() - TOKEN_REFRESH_SKEW_MS <= Date.now();\n if (!expired) return connection.accessToken;\n\n if (!connection.refreshToken) {\n // Legacy row from before refresh-token support: nothing to renew with.\n throw new LinearReauthRequiredError();\n }\n\n const existing = this.#inflightRefreshes.get(connection.orgId);\n if (existing) return existing;\n\n // The caller may hold a stale row: another request could have refreshed\n // and rotated the refresh token since this row was loaded. Reload before\n // refreshing so we don't burn the rotated token and force a false reauth.\n const latest = await this.loadConnection(connection.orgId);\n if (!latest) throw new LinearReauthRequiredError();\n\n const concurrent = this.#inflightRefreshes.get(connection.orgId);\n if (concurrent) return concurrent;\n\n const latestExpired = latest.expiresAt !== null && latest.expiresAt.getTime() - TOKEN_REFRESH_SKEW_MS <= Date.now();\n if (!latestExpired) return latest.accessToken;\n if (!latest.refreshToken) throw new LinearReauthRequiredError();\n\n const refreshToken = latest.refreshToken;\n const refresh = (async () => {\n try {\n const tokens = await this.refreshAccessToken(refreshToken);\n await this.#updateTokens(connection.orgId, tokens);\n return tokens.accessToken;\n } catch (err) {\n const status = (err as { status?: number }).status;\n // invalid_grant surfaces as 400/401: the refresh token was revoked or\n // already rotated away. Terminal for this connection.\n if (status === 400 || status === 401) throw new LinearReauthRequiredError();\n throw err;\n } finally {\n this.#inflightRefreshes.delete(connection.orgId);\n }\n })();\n this.#inflightRefreshes.set(connection.orgId, refresh);\n return refresh;\n }\n\n // ── Connection checks for agent tools ────────────────────────────────────\n\n /** Re-check an org's Linear connection (and its scopes) at most this often. */\n readonly #connectionChecks = new Map<string, LinearConnectionCheck>();\n\n /**\n * Whether the org has an active connection and whether its granted scope\n * allows posting comments. Cached per org with a short TTL — tool-set\n * resolution runs on every request.\n */\n async checkConnection(orgId: string): Promise<LinearConnectionCheck> {\n const cached = this.#connectionChecks.get(orgId);\n if (cached && Date.now() - cached.checkedAt < CONNECTION_TTL_MS) return cached;\n const connection = await this.loadConnection(orgId);\n const check: LinearConnectionCheck = {\n connected: connection !== null,\n canComment: connection !== null && this.canPostComments(connection),\n checkedAt: Date.now(),\n };\n this.#connectionChecks.set(orgId, check);\n return check;\n }\n\n /**\n * Drop the cached connection check for an org. Called after a connection is\n * persisted so the tools show up on the very next run instead of after the\n * TTL lapses.\n */\n invalidateConnectionCache(orgId: string): void {\n this.#connectionChecks.delete(orgId);\n }\n\n /**\n * A project's org never changes, so the resourceId → orgId mapping is\n * cached forever. `null` marks resource ids that aren't factory projects\n * (e.g. local default resources) so we don't re-query them on every\n * tool-set resolution.\n */\n readonly #orgIdByResourceId = new Map<string, string | null>();\n\n /** Map a session's resourceId to its owning org, or `null` when it isn't a project. */\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n // Non-UUID resource ids (local/dev resources) would make the uuid column\n // comparison throw — they're definitively \"not a project\", so cache that.\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n let orgId: string | null;\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n orgId = project?.orgId ?? null;\n } catch {\n // Transient database failure: skip the tools for this request but don't\n // cache the miss, so the next request retries the lookup.\n return null;\n }\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n }\n\n /** Test hook: clear the org/connection caches between specs. */\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n this.#connectionChecks.clear();\n }\n\n readonly intake: Intake = {\n resolveIntakeDispatch: input => this.#resolveIntakeDispatch(input),\n listSources: async ({ orgId }) => {\n const connection = await this.loadConnection(orgId);\n if (!connection) return [];\n const accessToken = await this.getFreshAccessToken(connection);\n const [projects, teams] = await Promise.all([this.listProjects(accessToken), this.listTeams(accessToken)]);\n return [\n ...projects.map(project => ({\n id: project.id,\n name: project.name,\n type: 'project' as const,\n })),\n ...teams.map(team => ({\n id: encodeSelfManagedTeamSourceId(team.id),\n name: team.name,\n type: 'team' as const,\n metadata: { teamKey: team.key },\n })),\n ];\n },\n listItems: async ({ orgId, sourceIds, attributionSourceIds, cursor }) => {\n if (sourceIds.length === 0) return { items: [], nextCursor: null };\n const connection = await this.loadConnection(orgId);\n if (!connection) return { items: [], nextCursor: null };\n const accessToken = await this.getFreshAccessToken(connection);\n const page = await this.#listIntakeIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds,\n attributionSourceIds,\n cursor,\n });\n return {\n items: page.issues.flatMap(issue => {\n if (!issue.sourceId) return [];\n return [\n {\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId: issue.sourceId,\n title: `${issue.identifier}: ${issue.title}`,\n status: issue.state ?? '',\n labels: issue.labels,\n assignee: issue.assignee,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n metadata: {\n identifier: issue.identifier,\n ...(issue.projectId ? { linearProjectId: issue.projectId } : {}),\n stateType: issue.stateType,\n priority: issue.priority,\n team: issue.source,\n },\n },\n ];\n }),\n nextCursor: page.nextCursor,\n };\n },\n listIssues: input => this.#listIntakeIssues(input),\n getIssue: input => this.#getIntakeIssue(input),\n createComment: input => this.#createIntakeComment(input),\n updateIssue: input => this.#updateIntakeIssue(input),\n };\n\n /**\n * Background-dispatch context: the org's OAuth connection with a fresh\n * token. Linear work items store the issue UUID directly as `externalId`.\n */\n async #resolveIntakeDispatch({\n orgId,\n externalSource,\n }: {\n orgId: string;\n externalSource: { type: string; externalId: string };\n }): Promise<{ connection: IntegrationConnection; issueId: string } | null> {\n if (externalSource.type !== 'issue') return null;\n const connection = await this.loadConnection(orgId);\n if (!connection) return null;\n const accessToken = await this.getFreshAccessToken(connection);\n return { connection: { type: 'oauth', accessToken }, issueId: externalSource.externalId };\n }\n /**\n * The OAuth connect/callback flow round-trips a signed `state` through\n * Linear, so a multi-replica deploy needs a deployment-stable state secret.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #clientId: string;\n readonly #clientSecret: string;\n\n readonly #rules: LinearEventRules;\n\n get rules(): LinearEventRules {\n return this.#rules;\n }\n\n constructor(config: LinearIntegrationConfig) {\n this.#rules = resolveLinearRules(config.rules);\n const missing = (['clientId', 'clientSecret'] as const).filter(key => !config[key]);\n if (missing.length > 0) {\n throw new Error(`LinearIntegration is missing required config: ${missing.join(', ')}.`);\n }\n this.#clientId = config.clientId;\n this.#clientSecret = config.clientSecret;\n }\n\n // ── OAuth ────────────────────────────────────────────────────────────────\n\n /**\n * Build the OAuth authorize URL. `prompt=consent` forces the workspace\n * picker even for an already-authorized user, so \"reconnect\" can switch\n * workspaces.\n */\n buildAuthorizeUrl(state: string, redirectUri: string): string {\n const url = new URL(LINEAR_AUTHORIZE_URL);\n url.searchParams.set('client_id', this.#clientId);\n url.searchParams.set('redirect_uri', redirectUri);\n url.searchParams.set('response_type', 'code');\n // `comments:create` lets the agent's linear_create_comment tool post\n // comments; everything else the integration does is read-only.\n url.searchParams.set('scope', 'read,comments:create');\n url.searchParams.set('state', state);\n url.searchParams.set('prompt', 'consent');\n return url.toString();\n }\n\n /** Exchange an OAuth `code` for a workspace-scoped token set. */\n async exchangeOAuthCode(code: string, redirectUri: string): Promise<LinearTokenSet> {\n return this.#requestTokens({ grant_type: 'authorization_code', code, redirect_uri: redirectUri }, 'token exchange');\n }\n\n /**\n * Exchange a refresh token for a new token set. Linear rotates refresh\n * tokens, so the returned set replaces the stored one entirely. A 400/401\n * here means the refresh token is invalid/revoked and the org must\n * re-authorize.\n */\n async refreshAccessToken(refreshToken: string): Promise<LinearTokenSet> {\n return this.#requestTokens({ grant_type: 'refresh_token', refresh_token: refreshToken }, 'token refresh');\n }\n\n /** POST to Linear's token endpoint and normalize the response. */\n async #requestTokens(params: Record<string, string>, label: string): Promise<LinearTokenSet> {\n const res = await fetch(LINEAR_TOKEN_URL, {\n method: 'POST',\n signal: AbortSignal.timeout(10_000),\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n ...params,\n client_id: this.#clientId,\n client_secret: this.#clientSecret,\n }),\n });\n if (!res.ok) {\n const err = new Error(`Linear ${label} failed (${res.status})`);\n (err as { status?: number }).status = res.status;\n throw err;\n }\n const body = (await res.json()) as {\n access_token?: string;\n refresh_token?: string;\n expires_in?: number;\n scope?: string;\n };\n if (!body.access_token) {\n throw new Error(`Linear ${label} returned no access token.`);\n }\n return {\n accessToken: body.access_token,\n refreshToken: body.refresh_token ?? null,\n expiresAt: typeof body.expires_in === 'number' ? new Date(Date.now() + body.expires_in * 1000) : null,\n scope: body.scope ?? null,\n };\n }\n\n // ── GraphQL reads/writes ─────────────────────────────────────────────────\n\n /** Fetch the workspace (organization) the access token is scoped to. */\n async fetchWorkspace(accessToken: string): Promise<LinearWorkspace> {\n const data = await linearGraphql<{ organization: { name: string; urlKey: string } }>(\n accessToken,\n `query { organization { name urlKey } }`,\n );\n return { name: data.organization.name, urlKey: data.organization.urlKey };\n }\n\n async #listIntakeIssues(input: ListIntakeIssuesInput): Promise<{ issues: IntakeIssue[]; nextCursor: string | null }> {\n const accessToken = getLinearAccessToken(input.connection);\n if (input.sourceIds.length === 0) return { issues: [], nextCursor: null };\n const attributionSourceIds = input.attributionSourceIds ?? input.sourceIds;\n const { projectIds, teamIds } = splitSelfManagedSourceIds(input.sourceIds);\n const cursors = decodeSelfManagedListCursor(input.cursor, input.sourceIds, attributionSourceIds);\n\n // Project-only intake still uses one Linear query, but its provider cursor\n // is wrapped so a later source-selection change cannot reinterpret it.\n if (teamIds.length === 0) {\n if (cursors.projects === null) return { issues: [], nextCursor: null };\n const result = await this.listActiveIssues(accessToken, cursors.projects, projectIds, input.labels);\n return {\n issues: result.issues.map(issue => linearIssueToIntakeIssue(issue)),\n nextCursor: encodeSelfManagedListCursor(\n { projects: result.nextCursor, teams: null },\n input.sourceIds,\n attributionSourceIds,\n ),\n };\n }\n\n // A team is selected. List projects and teams separately (the two Linear\n // filters would AND together in one query) and stamp each issue with the\n // selected source that surfaced it. Each source kind paginates on its own\n // cursor, carried in a compound cursor when both are present.\n const projectResult =\n projectIds.length > 0 && cursors.projects !== null\n ? await this.listActiveIssues(accessToken, cursors.projects, projectIds, input.labels)\n : { issues: [], nextCursor: null };\n const teamResult =\n cursors.teams !== null\n ? await this.listActiveIssues(accessToken, cursors.teams, undefined, input.labels, teamIds)\n : { issues: [], nextCursor: null };\n\n // Stamp project issues with their (selected) project id; stamp team issues\n // with the team source id. A team issue whose project was also selected is\n // reconciled by the dedupe step below (project wins).\n const projectIssues = projectResult.issues.map(issue => linearIssueToIntakeIssue(issue));\n const selectedTeamSourceById = new Map(teamIds.map(teamId => [teamId, encodeSelfManagedTeamSourceId(teamId)]));\n const selectedProjectIds = new Set(splitSelfManagedSourceIds(attributionSourceIds).projectIds);\n const teamIssues = teamResult.issues\n .filter(issue => issue.projectId === null || !selectedProjectIds.has(issue.projectId))\n .map(issue => {\n const teamSourceId = issue.teamId ? selectedTeamSourceById.get(issue.teamId) : undefined;\n if (!teamSourceId) throw new Error('Linear returned an issue outside the selected teams.');\n return { ...linearIssueToIntakeIssue(issue), sourceId: teamSourceId };\n });\n\n const deduped = dedupeSelfManagedIssues([...projectIssues, ...teamIssues]);\n return {\n issues: deduped,\n nextCursor: encodeSelfManagedListCursor(\n { projects: projectResult.nextCursor, teams: teamResult.nextCursor },\n input.sourceIds,\n attributionSourceIds,\n ),\n };\n }\n\n async #getIntakeIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null> {\n const accessToken = getLinearAccessToken(input.connection);\n const issue = await this.fetchIssueDetail(accessToken, input.issueId);\n if (!issue) return null;\n return {\n ...linearIssueToIntakeIssue(issue),\n description: issue.description,\n commentCount: issue.comments.length,\n comments: issue.comments,\n };\n }\n\n async #createIntakeComment(input: CreateIntakeCommentInput): Promise<{ id: string; url: string } | null> {\n const accessToken = getLinearAccessToken(input.connection);\n return this.createIssueComment(accessToken, input.issueId, input.body);\n }\n\n async #updateIntakeIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null> {\n const accessToken = getLinearAccessToken(input.connection);\n const issue = await this.fetchIssueDetail(accessToken, input.issueId);\n if (!issue) return null;\n const teamKey = issue.team;\n if (!teamKey) return null;\n const states = await this.#listTeamWorkflowStates(accessToken, teamKey);\n let targetState: { id: string; name: string; type: string } | null = null;\n if (input.state.kind === 'byType') {\n const wantedType = input.state.stateType;\n targetState = states.find(state => state.type === wantedType) ?? null;\n } else {\n const wanted = input.state.name.toLowerCase();\n targetState = states.find(state => state.name.toLowerCase() === wanted) ?? null;\n }\n if (!targetState) return null;\n if (targetState.name === issue.state) {\n return linearIssueToIntakeIssue(issue);\n }\n const data = await linearGraphql<{ issueUpdate: { success: boolean } }>(\n accessToken,\n `mutation UpdateIssueState($id: String!, $stateId: String!) {\n issueUpdate(id: $id, input: { stateId: $stateId }) { success }\n }`,\n { id: issue.id, stateId: targetState.id },\n );\n if (!data.issueUpdate.success) {\n throw new Error('Linear did not accept the issue update.');\n }\n const fresh = await this.fetchIssueDetail(accessToken, issue.id);\n if (!fresh) return null;\n return linearIssueToIntakeIssue(fresh);\n }\n\n async #listTeamWorkflowStates(\n accessToken: string,\n teamKey: string,\n ): Promise<Array<{ id: string; name: string; type: string }>> {\n const data = await linearGraphql<{\n team: { states: { nodes: Array<{ id: string; name: string; type: string }> } } | null;\n }>(\n accessToken,\n `query TeamStates($key: String!) {\n team(id: $key) { states(first: 100) { nodes { id name type } } }\n }`,\n { key: teamKey },\n );\n return data.team?.states.nodes ?? [];\n }\n\n /** List the workspace's projects (for the Settings intake-source picker). */\n async listProjects(accessToken: string): Promise<LinearProject[]> {\n const data = await linearGraphql<{\n projects: {\n nodes: Array<{\n id: string;\n name: string;\n state: string;\n teams: { nodes: Array<{ id: string; key: string; name: string }> };\n }>;\n };\n }>(\n accessToken,\n `query { projects(first: 100) { nodes { id name state teams(first: 10) { nodes { id key name } } } } }`,\n );\n return data.projects.nodes.map(node => ({\n id: node.id,\n name: node.name,\n state: node.state,\n teams: node.teams.nodes.map(team => ({ id: team.id, key: team.key, name: team.name })),\n }));\n }\n\n /** List the workspace's teams (for the Settings intake-source picker). */\n async listTeams(accessToken: string): Promise<LinearTeam[]> {\n const teams: Array<{ id: string; key: string; name: string }> = [];\n let after: string | undefined;\n for (let page = 0; page < LINEAR_TEAMS_MAX_PAGES; page += 1) {\n const data = await linearGraphql<{\n teams: {\n nodes: Array<{ id: string; key: string; name: string }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n }>(\n accessToken,\n `query Teams($first: Int!, $after: String) {\n teams(first: $first, after: $after) {\n nodes { id key name }\n pageInfo { hasNextPage endCursor }\n }\n }`,\n { first: LINEAR_TEAMS_PAGE_SIZE, ...(after ? { after } : {}) },\n );\n teams.push(...data.teams.nodes);\n if (!data.teams.pageInfo.hasNextPage || !data.teams.pageInfo.endCursor) break;\n // A page that hands back the cursor it was asked for would replay forever.\n if (data.teams.pageInfo.endCursor === after) throw invalidLinearCursor();\n after = data.teams.pageInfo.endCursor;\n }\n return teams.map(team => ({\n id: team.id,\n key: team.key,\n name: team.name,\n sourceId: encodeSelfManagedTeamSourceId(team.id),\n }));\n }\n\n sourceMatchesIssue(sourceId: string, issue: Pick<LinearIssueDetail, 'projectId' | 'teamId'>): boolean {\n return isSelfManagedTeamSourceId(sourceId)\n ? issue.teamId === decodeSelfManagedTeamSourceId(sourceId)\n : issue.projectId === sourceId;\n }\n\n /**\n * List one page of the workspace's active issues (triage/backlog/unstarted/\n * started — completed and canceled are excluded), most recently updated\n * first. When `projectIds` is provided, only issues from those projects are\n * returned. When `teamIds` is provided, only issues in those teams are\n * returned, including issues that belong to no project. Callers list team\n * sources and project sources in separate calls so the two filters are not\n * AND-ed together.\n */\n async listActiveIssues(\n accessToken: string,\n after?: string,\n projectIds?: string[],\n labels?: string[],\n teamIds?: string[],\n ): Promise<LinearIssuePage> {\n const normalizedLabels = [...new Set((labels ?? []).map(label => label.trim()).filter(Boolean))];\n const projectFilter = projectIds?.length ? ', project: { id: { in: $projectIds } }' : '';\n const projectVar = projectIds?.length ? ', $projectIds: [ID!]' : '';\n const teamFilter = teamIds?.length ? ', team: { id: { in: $teamIds } }' : '';\n const teamVar = teamIds?.length ? ', $teamIds: [ID!]' : '';\n const labelFilter = normalizedLabels.length > 0 ? ', labels: { name: { in: $labels } }' : '';\n const labelVar = normalizedLabels.length > 0 ? ', $labels: [String!]' : '';\n const data = await linearGraphql<IssuesQueryData>(\n accessToken,\n `query Intake($first: Int!, $after: String${projectVar}${teamVar}${labelVar}) {\n issues(\n first: $first\n after: $after\n orderBy: updatedAt\n filter: { state: { type: { in: [\"triage\", \"backlog\", \"unstarted\", \"started\"] } }${projectFilter}${teamFilter}${labelFilter} }\n ) {\n nodes {\n id\n identifier\n title\n url\n priorityLabel\n createdAt\n updatedAt\n state { name type }\n project { id }\n assignee { name }\n creator { name }\n team { id key }\n labels { nodes { name } }\n }\n pageInfo { hasNextPage endCursor }\n }\n }`,\n {\n first: LINEAR_ISSUES_PAGE_SIZE,\n after: after ?? null,\n ...(projectIds?.length ? { projectIds } : {}),\n ...(teamIds?.length ? { teamIds } : {}),\n ...(normalizedLabels.length > 0 ? { labels: normalizedLabels } : {}),\n },\n );\n const { nodes, pageInfo } = data.issues;\n return {\n issues: nodes.map(node => ({\n id: node.id,\n projectId: node.project?.id ?? null,\n identifier: node.identifier,\n title: node.title,\n url: node.url,\n state: node.state.name,\n stateType: node.state.type,\n priorityLabel: node.priorityLabel,\n assignee: node.assignee?.name ?? null,\n creator: node.creator?.name ?? null,\n team: node.team?.key ?? null,\n labels: node.labels.nodes.map(label => label.name),\n createdAt: node.createdAt,\n updatedAt: node.updatedAt,\n teamId: node.team?.id ?? null,\n })),\n nextCursor: pageInfo.hasNextPage ? pageInfo.endCursor : null,\n };\n }\n\n /** Follow `comments.pageInfo` until exhausted so long discussions aren't truncated. */\n async #fetchRemainingIssueComments(\n accessToken: string,\n issueId: string,\n firstPage: IssueCommentsPage,\n ): Promise<IssueCommentNode[]> {\n const nodes = [...firstPage.nodes];\n let { hasNextPage, endCursor } = firstPage.pageInfo;\n for (let page = 1; hasNextPage && endCursor && page < ISSUE_COMMENTS_MAX_PAGES; page++) {\n const data = await linearGraphql<IssueCommentsQueryData>(\n accessToken,\n `query IssueComments($id: String!, $first: Int!, $after: String!) {\n issue(id: $id) {\n comments(first: $first, after: $after) {\n nodes { body createdAt user { name } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }`,\n { id: issueId, first: ISSUE_COMMENTS_PAGE_SIZE, after: endCursor },\n );\n const comments = data.issue?.comments;\n if (!comments) break;\n nodes.push(...comments.nodes);\n if (comments.pageInfo.hasNextPage && comments.pageInfo.endCursor === endCursor) throw invalidLinearCursor();\n ({ hasNextPage, endCursor } = comments.pageInfo);\n }\n return nodes;\n }\n\n /**\n * Fetch one issue with its description and comments. `idOrIdentifier`\n * accepts both the Linear UUID and the human key (`ENG-123`). Returns\n * `null` when the issue doesn't exist (Linear reports it as an \"Entity not\n * found\" error).\n */\n async fetchIssueDetail(\n accessToken: string,\n idOrIdentifier: string,\n _sourceIds?: string[],\n _routedSourceIds?: string[],\n ): Promise<LinearIssueDetail | null> {\n let data: IssueDetailQueryData;\n try {\n data = await linearGraphql<IssueDetailQueryData>(\n accessToken,\n `query IssueDetail($id: String!, $commentsFirst: Int!) {\n issue(id: $id) {\n id\n identifier\n title\n description\n url\n priorityLabel\n createdAt\n updatedAt\n state { name type }\n project { id }\n assignee { name }\n creator { name }\n team { id key }\n labels { nodes { name } }\n comments(first: $commentsFirst) {\n nodes { body createdAt user { name } }\n pageInfo { hasNextPage endCursor }\n }\n }\n }`,\n { id: idOrIdentifier, commentsFirst: ISSUE_COMMENTS_PAGE_SIZE },\n );\n } catch (err) {\n // Linear surfaces unknown ids/identifiers as a GraphQL \"Entity not\n // found\" error rather than a null node — map that to \"issue doesn't\n // exist\".\n if (err instanceof Error && /entity not found/i.test(err.message)) return null;\n throw err;\n }\n const issue = data.issue;\n if (!issue) return null;\n const allComments = await this.#fetchRemainingIssueComments(accessToken, issue.id, issue.comments);\n const comments = allComments.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n return {\n id: issue.id,\n projectId: issue.project?.id ?? null,\n teamId: issue.team?.id ?? null,\n identifier: issue.identifier,\n title: issue.title,\n description: issue.description?.trim() ? issue.description : null,\n url: issue.url,\n state: issue.state.name,\n stateType: issue.state.type,\n priorityLabel: issue.priorityLabel,\n assignee: issue.assignee?.name ?? null,\n creator: issue.creator?.name ?? null,\n team: issue.team?.key ?? null,\n labels: issue.labels.nodes.map(label => label.name),\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n comments: comments.map(comment => ({\n author: comment.user?.name ?? null,\n body: comment.body,\n createdAt: comment.createdAt,\n })),\n };\n }\n\n /**\n * Post a comment on an issue. `idOrIdentifier` accepts both the Linear UUID\n * and the human key (`ENG-123`) — the identifier is resolved to a UUID\n * first because `commentCreate` only accepts UUIDs. Returns `null` when the\n * issue doesn't exist.\n */\n async createIssueComment(\n accessToken: string,\n idOrIdentifier: string,\n body: string,\n ): Promise<LinearCreatedComment | null> {\n let issueId: string;\n try {\n const data = await linearGraphql<IssueIdQueryData>(\n accessToken,\n `query IssueId($id: String!) { issue(id: $id) { id } }`,\n { id: idOrIdentifier },\n );\n if (!data.issue) return null;\n issueId = data.issue.id;\n } catch (err) {\n if (err instanceof Error && /entity not found/i.test(err.message)) return null;\n throw err;\n }\n const data = await linearGraphql<CommentCreateMutationData>(\n accessToken,\n `mutation CommentCreate($input: CommentCreateInput!) {\n commentCreate(input: $input) { success comment { id url } }\n }`,\n { input: { issueId, body } },\n );\n if (!data.commentCreate.success || !data.commentCreate.comment) {\n throw new Error('Linear did not accept the comment.');\n }\n return data.commentCreate.comment;\n }\n\n // ── FactoryIntegration surface ───────────────────────────────────────────\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (!linearIssueReconciliationEnabled()) return [];\n const reconcile = attachLinearIssueReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = linearIssueReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * The integration's HTTP surface: `/web/linear/*` + `/auth/linear/*` Mastra\n * `apiRoutes` (status, OAuth connect/callback, projects + issues for\n * Intake). Handlers operate on this instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n return buildLinearRoutes({\n linear: this,\n auth: ctx.auth,\n stateSigner: ctx.stateSigner,\n baseUrl: ctx.baseUrl,\n intake: ctx.storage.intake,\n projects: ctx.storage.projects,\n ingestFactoryIssues: attachLinearRules(this, ctx),\n workItems: ctx.runtime?.workItems,\n boards: ctx.runtime?.boards,\n });\n }\n\n /**\n * Org-scoped agent tools: issue detail + comment tools for sessions whose\n * project belongs to an org with an active Linear connection.\n */\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildLinearAgentTools({ requestContext: args.requestContext, linear: this });\n }\n\n /** Non-secret config snapshot for system diagnostics/startup logs. */\n diagnostics(): Record<string, unknown> {\n return {\n oauthAppConfigured: true,\n };\n }\n}\n\nfunction getLinearAccessToken(connection: IntegrationConnection): string {\n if (connection.type !== 'oauth') {\n throw new Error('Linear capabilities require an OAuth connection.');\n }\n return connection.accessToken;\n}\n\n/**\n * Self-managed source ids. Projects use their raw Linear project id (no prefix,\n * preserving existing intake bindings). Teams are prefixed so the two never\n * collide and callers can tell them apart.\n */\nconst SELF_MANAGED_TEAM_SOURCE_PREFIX = 'linear-team:';\n\nfunction encodeSelfManagedTeamSourceId(teamId: string): string {\n return `${SELF_MANAGED_TEAM_SOURCE_PREFIX}${teamId}`;\n}\n\nfunction isSelfManagedTeamSourceId(sourceId: string): boolean {\n return sourceId.startsWith(SELF_MANAGED_TEAM_SOURCE_PREFIX);\n}\n\nfunction decodeSelfManagedTeamSourceId(sourceId: string): string {\n return sourceId.slice(SELF_MANAGED_TEAM_SOURCE_PREFIX.length);\n}\n\n/**\n * Split selected source ids into raw project ids and raw team ids. A team\n * source id carries the `linear-team:` prefix; everything else is a project id.\n */\nfunction splitSelfManagedSourceIds(sourceIds: string[]): { projectIds: string[]; teamIds: string[] } {\n const projectIds: string[] = [];\n const teamIds: string[] = [];\n for (const sourceId of sourceIds) {\n if (isSelfManagedTeamSourceId(sourceId)) teamIds.push(decodeSelfManagedTeamSourceId(sourceId));\n else projectIds.push(sourceId);\n }\n return { projectIds, teamIds };\n}\n\ntype SelfManagedListCursor = {\n v: 1;\n sourceSet: string;\n projects: string | null;\n teams: string | null;\n};\n\nfunction linearSourceSetFingerprint(sourceIds: string[], attributionSourceIds: string[]): string {\n const scope = {\n sourceIds: [...new Set(sourceIds)].sort(),\n attributionSourceIds: [...new Set(attributionSourceIds)].sort(),\n };\n return createHash('sha256').update(JSON.stringify(scope)).digest('base64url');\n}\n\nfunction invalidLinearCursor(): Error {\n return Object.assign(new Error('Linear cursor is invalid or stale.'), { code: 'invalid_cursor' as const });\n}\n\nfunction isCursorValue(value: unknown): value is string | null {\n return value === null || typeof value === 'string';\n}\n\nfunction decodeSelfManagedListCursor(\n cursor: string | undefined,\n sourceIds: string[],\n attributionSourceIds: string[],\n): { projects: string | null | undefined; teams: string | null | undefined } {\n const { projectIds, teamIds } = splitSelfManagedSourceIds(sourceIds);\n if (!cursor) {\n return {\n projects: projectIds.length > 0 ? undefined : null,\n teams: teamIds.length > 0 ? undefined : null,\n };\n }\n try {\n const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as Partial<SelfManagedListCursor>;\n if (\n parsed.v !== 1 ||\n parsed.sourceSet !== linearSourceSetFingerprint(sourceIds, attributionSourceIds) ||\n !isCursorValue(parsed.projects) ||\n !isCursorValue(parsed.teams)\n ) {\n throw invalidLinearCursor();\n }\n return {\n projects: parsed.projects,\n teams: parsed.teams,\n };\n } catch {\n throw invalidLinearCursor();\n }\n}\n\nfunction encodeSelfManagedListCursor(\n state: Pick<SelfManagedListCursor, 'projects' | 'teams'>,\n sourceIds: string[],\n attributionSourceIds: string[],\n): string | null {\n if (state.projects === null && state.teams === null) return null;\n return Buffer.from(\n JSON.stringify({\n v: 1,\n sourceSet: linearSourceSetFingerprint(sourceIds, attributionSourceIds),\n ...state,\n } satisfies SelfManagedListCursor),\n ).toString('base64url');\n}\n\n/**\n * Deduplicate issues that surfaced from both a selected team and one of its\n * selected projects. Keeps one entry per Linear issue UUID.\n *\n * Tie-breaker — MOST-SPECIFIC-WINS: an issue in a selected project is\n * attributed to that project source (routes to the project's board); the team\n * source covers only the remainder (projectless issues and issues in projects\n * that were not separately selected). Change the comparison here to change the\n * routing policy — this is the single precedence point for the self-managed\n * integration, mirroring the platform-backed one.\n */\nfunction dedupeSelfManagedIssues(\n issues: Array<IntakeIssue & { sourceId?: string | null }>,\n): Array<IntakeIssue & { sourceId?: string | null }> {\n const isProjectSource = (sourceId: string | null | undefined): boolean =>\n typeof sourceId === 'string' && sourceId.length > 0 && !isSelfManagedTeamSourceId(sourceId);\n const winners = new Map<string, IntakeIssue & { sourceId?: string | null }>();\n for (const issue of issues) {\n const existing = winners.get(issue.id);\n if (!existing) {\n winners.set(issue.id, issue);\n continue;\n }\n // Project source beats team source; otherwise keep the first seen.\n if (isProjectSource(issue.sourceId) && !isProjectSource(existing.sourceId)) {\n winners.set(issue.id, issue);\n }\n }\n const seen = new Set<string>();\n const ordered: Array<IntakeIssue & { sourceId?: string | null }> = [];\n for (const issue of issues) {\n if (seen.has(issue.id)) continue;\n seen.add(issue.id);\n ordered.push(winners.get(issue.id)!);\n }\n return ordered;\n}\n\nfunction linearIssueToIntakeIssue(issue: Omit<LinearIssue, 'projectId'> & { projectId?: string | null }): IntakeIssue {\n return {\n id: issue.id,\n sourceId: issue.projectId ?? null,\n projectId: issue.projectId ?? null,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.creator,\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priorityLabel,\n assignee: issue.assignee,\n source: issue.team,\n labels: issue.labels,\n commentCount: null,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AA6G7B,MAAM,0BAA0B;AAChC,MAAM,2BAA2B;AACjC,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;;AAE/B,MAAM,2BAA2B;;AAGjC,MAAM,wBAAwB;;AAG9B,MAAM,oBAAoB;AAE1B,MAAM,eAAe;;AAGrB,IAAa,4BAAb,cAA+C,MAAM;CACnD,cAAc;EACZ,MAAM,+EAA+E;CACvF;AACF;;AA2EA,eAAe,cAAiB,aAAqB,OAAe,WAAiD;CACnH,MAAM,MAAM,MAAM,MAAM,oBAAoB;EAC1C,QAAQ;EACR,QAAQ,YAAY,QAAQ,IAAM;EAClC,SAAS;GACP,gBAAgB;GAChB,eAAe,UAAU;EAC3B;EACA,MAAM,KAAK,UAAU;GAAE;GAAO;EAAU,CAAC;CAC3C,CAAC;CACD,IAAI,CAAC,IAAI,IAAI;EAGX,IAAI,SAAwB;EAC5B,IAAI;GAEF,UAAS,MADc,IAAI,KAAK,EAAA,CACf,SAAS,EAAE,EAAE,WAAW;EAC3C,QAAQ,CAER;EACA,MAAM,sBAAM,IAAI,MAAM,8BAA8B,IAAI,OAAO,GAAG,SAAS,KAAK,WAAW,IAAI;EAC/F,IAA6B,SAAS,IAAI;EAC1C,MAAM;CACR;CACA,MAAM,OAAQ,MAAM,IAAI,KAAK;CAC7B,IAAI,KAAK,QAAQ,QACf,MAAM,IAAI,MAAM,qBAAqB,KAAK,OAAO,EAAE,EAAE,WAAW,iBAAiB;CAEnF,IAAI,CAAC,KAAK,MACR,MAAM,IAAI,MAAM,8BAA8B;CAEhD,OAAO,KA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M,qBAAqB,GAAG,eAAe,CAAC;AAoBpD,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,OAAO,CAAC,EACnD,OAAO,EAAE,kBAAkB,GAC1B,qBAAqB,GAAG,SAAS,CA6CnC"}
1
+ {"version":3,"file":"issue-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/issue-reconciler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAI1D,MAAM,MAAM,qBAAqB,GAAG,eAAe,CAAC;AAsBpD,wBAAgB,2BAA2B,CACzC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,OAAO,CAAC,EACnD,OAAO,EAAE,kBAAkB,GAC1B,qBAAqB,GAAG,SAAS,CA8CnC"}
@@ -16,6 +16,8 @@ function issueToIngress(issue) {
16
16
  creator: issue.author ?? null,
17
17
  team: issue.source ?? null,
18
18
  labels: [...issue.labels ?? []],
19
+ sourceId: issue.sourceId,
20
+ projectId: issue.projectId,
19
21
  createdAt: issue.createdAt,
20
22
  updatedAt: issue.updatedAt
21
23
  };
@@ -42,6 +44,7 @@ function attachLinearIssueReconciler(linear, context) {
42
44
  },
43
45
  metadata: (_item, issue) => ({
44
46
  linearIssueId: issue.id,
47
+ ...issue.projectId ? { linearProjectId: issue.projectId } : {},
45
48
  identifier: issue.identifier,
46
49
  linearState: issue.state,
47
50
  linearStateType: issue.stateType,
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/linear/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport type { IntegrationContext } from '../base.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearRules } from './rules.js';\nimport type { LinearIssueIngress } from './rules.js';\n\nexport type LinearIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(issue: import('../../capabilities/intake.js').IntakeIssue): LinearIssueIngress {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n creator: issue.author ?? null,\n team: issue.source ?? null,\n labels: [...(issue.labels ?? [])],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nexport function attachLinearIssueReconciler(\n linear: Pick<LinearIntegration, 'intake' | 'rules'>,\n context: IntegrationContext,\n): LinearIssueReconciler | undefined {\n if (!context.runtime || !linear.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n linearRules: linear.rules,\n });\n\n return createIssueReconciler({\n integrationId: 'linear',\n intake: linear.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n isTerminal: item => workItemPhaseSemantics(boards, item)?.kind === 'terminal',\n issueId: item => {\n const issueId = item.metadata?.linearIssueId;\n return typeof issueId === 'string' && issueId.length > 0 ? issueId : undefined;\n },\n metadata: (_item, issue) => ({\n linearIssueId: issue.id,\n identifier: issue.identifier,\n linearState: issue.state,\n linearStateType: issue.stateType,\n linearPriority: issue.priority,\n linearAssignee: issue.assignee,\n linearCreator: issue.author,\n linearTeam: issue.source,\n assignee: issue.assignee,\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(issue)],\n });\n },\n });\n}\n"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AAM,MAAM,OAAO;IACjB,OAAO,QAAQ;IACf,QAAQ;IACR,kBAAkB,QAAQ;IAC1B,QAAQ,CAAC,eAAe,KAAK,CAAC;GAChC,CAAC;EACH;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/linear/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport type { IntegrationContext } from '../base.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearRules } from './rules.js';\nimport type { LinearIssueIngress } from './rules.js';\n\nexport type LinearIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(issue: import('../../capabilities/intake.js').IntakeIssue): LinearIssueIngress {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n creator: issue.author ?? null,\n team: issue.source ?? null,\n labels: [...(issue.labels ?? [])],\n sourceId: issue.sourceId,\n projectId: issue.projectId,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nexport function attachLinearIssueReconciler(\n linear: Pick<LinearIntegration, 'intake' | 'rules'>,\n context: IntegrationContext,\n): LinearIssueReconciler | undefined {\n if (!context.runtime || !linear.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n linearRules: linear.rules,\n });\n\n return createIssueReconciler({\n integrationId: 'linear',\n intake: linear.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n isTerminal: item => workItemPhaseSemantics(boards, item)?.kind === 'terminal',\n issueId: item => {\n const issueId = item.metadata?.linearIssueId;\n return typeof issueId === 'string' && issueId.length > 0 ? issueId : undefined;\n },\n metadata: (_item, issue) => ({\n linearIssueId: issue.id,\n ...(issue.projectId ? { linearProjectId: issue.projectId } : {}),\n identifier: issue.identifier,\n linearState: issue.state,\n linearStateType: issue.stateType,\n linearPriority: issue.priority,\n linearAssignee: issue.assignee,\n linearCreator: issue.author,\n linearTeam: issue.source,\n assignee: issue.assignee,\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(issue)],\n });\n },\n });\n}\n"],"mappings":";;;;;AAUA,SAAS,eAAe,OAA+E;CACrG,OAAO;EACL,IAAI,MAAM;EACV,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,OAAO,MAAM,SAAS;EACtB,WAAW,MAAM,aAAa;EAC9B,eAAe,MAAM,YAAY;EACjC,UAAU,MAAM,YAAY;EAC5B,SAAS,MAAM,UAAU;EACzB,MAAM,MAAM,UAAU;EACtB,QAAQ,CAAC,GAAI,MAAM,UAAU,CAAC,CAAE;EAChC,UAAU,MAAM;EAChB,WAAW,MAAM;EACjB,WAAW,MAAM;EACjB,WAAW,MAAM;CACnB;AACF;AAEA,SAAgB,4BACd,QACA,SACmC;CACnC,IAAI,CAAC,QAAQ,WAAW,CAAC,OAAO,OAAO,uBAAuB,OAAO,KAAA;CACrE,MAAM,SAAS,QAAQ,QAAQ;CAE/B,MAAM,QAAQ,IAAI,YAAY;EAC5B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B;EACA,aAAa,OAAO;CACtB,CAAC;CAED,OAAO,sBAAsB;EAC3B,eAAe;EACf,QAAQ,OAAO;EACf,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,aAAY,SAAQ,uBAAuB,QAAQ,IAAI,CAAC,EAAE,SAAS;EACnE,UAAS,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,CAuV/E"}
@@ -297,7 +297,8 @@ function buildLinearRoutes(options) {
297
297
  labels: issue.labels,
298
298
  createdAt: issue.createdAt,
299
299
  updatedAt: issue.updatedAt,
300
- sourceId: issue.sourceId ?? null
300
+ sourceId: issue.sourceId ?? null,
301
+ projectId: issue.projectId ?? null
301
302
  }));
302
303
  if (factoryProjectId && intakeBoards && options.ingestFactoryIssues) await options.ingestFactoryIssues({
303
304
  orgId: resolved.tenant.orgId,
@@ -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;CAG7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AM,OAAO,iBAAiB,aAAa,gBAAgB,aAAa,cAAc;IACpG,MAAM,mBAAmB,YAAY,KAAA,IAAY,OAAO,OAAO,UAAU,OAAO,eAAe;IAC/F,MAAM,kBAAkB,QAAQ,sBAAsB,QAAQ,aAAa,KAAK,IAAI;IACpF,MAAM,WAAW,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"}
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,E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ACJ,QAAQ,QACR,EAAE,QAAQ,SAAS,mBAAmB,QAAQ,QAAQ,IAAI,IAAI,2BAA2B,KAAK,MAAM;GACtG,IAAI,gBAAgB,WAAW,KAAK,CAAC,eAAe,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;GACnG,MAAM,iBAAiB,gBAAgB,cAAc;GAErD,IAAI;IACF,MAAM,cAAc,MAAM,OAAO,oBAAoB,UAAU;IAC/D,MAAM,QAAQ,MAAM,OAAO,iBAAiB,aAAa,gBAAgB,aAAa,cAAc;IACpG,MAAM,mBAAmB,YAAY,KAAA,IAAY,OAAO,OAAO,UAAU,OAAO,eAAe;IAC/F,MAAM,kBAAkB,QAAQ,sBAAsB,QAAQ,aAAa,KAAK,IAAI;IACpF,MAAM,WAAW,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,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