@mastra/factory 0.2.1-alpha.2 → 0.2.1-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +3462 -3583
- package/dist/factory.js.map +1 -1
- package/dist/index.js +3462 -3583
- package/dist/index.js.map +1 -1
- package/dist/integrations/base.d.ts +13 -25
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +625 -217
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/routes.d.ts +1 -4
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +113 -203
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +30 -0
- package/dist/integrations/github/rules.d.ts.map +1 -0
- package/dist/{rules/github-service.js → integrations/github/rules.js} +27 -8
- package/dist/integrations/github/rules.js.map +1 -0
- package/dist/integrations/linear/agent-tools.js.map +1 -1
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +352 -3
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts +2 -2
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +2 -2
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts +42 -0
- package/dist/integrations/linear/rules.d.ts.map +1 -0
- package/dist/{rules/linear-service.js → integrations/linear/rules.js} +14 -4
- package/dist/integrations/linear/rules.js.map +1 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +626 -218
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +353 -3
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/routes/oauth.js +6 -39
- package/dist/routes/oauth.js.map +1 -1
- package/dist/routes/surface.d.ts +3 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +230 -619
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +74 -75
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/metrics.js.map +1 -1
- package/package.json +5 -5
- package/dist/integrations/github/project-lock.d.ts +0 -100
- package/dist/integrations/github/project-lock.d.ts.map +0 -1
- package/dist/integrations/github/project-lock.js +0 -103
- package/dist/integrations/github/project-lock.js.map +0 -1
- package/dist/rules/github-service.d.ts +0 -29
- package/dist/rules/github-service.d.ts.map +0 -1
- package/dist/rules/github-service.js.map +0 -1
- package/dist/rules/linear-service.d.ts +0 -27
- package/dist/rules/linear-service.d.ts.map +0 -1
- package/dist/rules/linear-service.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/integrations/linear/routes.ts","../../../src/integrations/linear/agent-tools.ts","../../../src/integrations/linear/integration.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 type { RouteAuth } from '../../routes/route.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { IntegrationHooks } from '../base.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\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 hooks?: IntegrationHooks;\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 > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Linear read failure to the API response for the SPA. */\nfunction linearFetchError(c: RouteContext, err: unknown) {\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 active issues (cursor-paged) ───────────────────\n // Respects the caller'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({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n integrationIds: ['linear'],\n });\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 projects selected means nothing is synced — don't fan out to Linear.\n const projectIds = selection.sourceIds ?? [];\n if (projectIds.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: projectIds,\n cursor: after,\n });\n const issuePayload = issues.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 team: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }));\n if (factoryProjectId && options.hooks?.ingestLinearIssues) {\n await options.hooks.ingestLinearIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n","/**\n * Linear tools exposed to the coding agent.\n *\n * Wired into the agent through the SDK's async `extraTools` provider: on each\n * tool-set resolution we map the session's resourceId (the factory project id)\n * to its owning org and only expose the Linear tools when that org has a\n * Linear connection. Projects whose org never connected Linear (or when the\n * feature is disabled) see no Linear tools at all — the model is never shown\n * tools it can't use.\n *\n * Tenancy mirrors the Linear API routes: everything is scoped by the org that\n * owns the project, and tokens are refreshed through the integration's shared\n * connection lifecycle.\n */\n\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\nfunction createLinearGetIssueTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_get_issue',\n description:\n \"Fetch a Linear issue's full details — title, description, state, assignee, labels, priority, and discussion comments. Use this whenever you're working on a Linear issue (e.g. ENG-123) to get its complete context.\",\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n }),\n execute: async ({ issue }: { issue: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to fetch issues.' };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const detail = await linear.intake.getIssue({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n });\n if (!detail) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return detail;\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to fetch Linear issue: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearCommentTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_create_comment',\n description:\n 'Post a comment on a Linear issue (e.g. to report investigation findings, link a PR, or ask a clarifying question). The comment is posted as the connected Linear integration, so make clear it comes from the agent.',\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n body: z.string().min(1).describe('The comment body, as Linear-flavored markdown.'),\n }),\n execute: async ({ issue, body }: { issue: string; body: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to post comments.' };\n }\n if (!linear.canPostComments(connection)) {\n return {\n error: 'The Linear connection does not have comment permissions. Reconnect Linear in Settings to grant them.',\n };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const comment = await linear.intake.createComment({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n body,\n });\n if (!comment) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return { posted: true, url: comment.url };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to post Linear comment: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\n/**\n * Async `extraTools` provider: expose Linear tools only when the session's\n * project belongs to an org with an active Linear connection.\n */\nexport async function buildLinearAgentTools({\n requestContext,\n linear,\n}: {\n requestContext: RequestContext;\n /** The integration instance providing the Linear API client. */\n linear: LinearIntegration;\n}): Promise<Record<string, ReturnType<typeof createLinearGetIssueTool> | ReturnType<typeof createLinearCommentTool>>> {\n if (!linear.authEnabled) return {};\n\n const ctx = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const resourceId = ctx?.resourceId;\n if (!resourceId) return {};\n\n const orgId = await linear.resolveOrgId(resourceId);\n if (!orgId) return {};\n const check = await linear.checkConnection(orgId);\n if (!check.connected) return {};\n\n return {\n linear_get_issue: createLinearGetIssueTool(linear, orgId),\n // Only offered when the granted OAuth scope allows posting comments —\n // connections made before `comments:create` was requested are read-only\n // until the org reconnects Linear.\n ...(check.canComment ? { linear_create_comment: createLinearCommentTool(linear, orgId) } : {}),\n };\n}\n","/**\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 type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\n\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 { buildLinearAgentTools } from './agent-tools.js';\nimport { buildLinearRoutes } from './routes.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 for the Linear OAuth application. All fields are required. */\nexport interface LinearIntegrationConfig {\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;\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 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\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;\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 };\n assignee: { name: string } | null;\n team: { 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 };\n assignee: { name: string } | null;\n team: { 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 = await this.listProjects(accessToken);\n return projects.map(project => ({\n id: project.id,\n name: project.name,\n type: 'project',\n }));\n },\n listItems: async ({ orgId, sourceIds, 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.listActiveIssues(accessToken, cursor, sourceIds);\n return {\n items: page.issues.map(issue => ({\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId: issue.projectId,\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.priorityLabel,\n team: issue.team,\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 constructor(config: LinearIntegrationConfig) {\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 const result = await this.listActiveIssues(accessToken, input.cursor, input.sourceIds, input.labels);\n return {\n issues: result.issues.map(issue => linearIssueToIntakeIssue(issue)),\n nextCursor: result.nextCursor,\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 /**\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.\n */\n async listActiveIssues(\n accessToken: string,\n after?: string,\n projectIds?: string[],\n labels?: 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 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}${labelVar}) {\n issues(\n first: $first\n after: $after\n orderBy: updatedAt\n filter: { state: { type: { in: [\"triage\", \"backlog\", \"unstarted\", \"started\"] } }${projectFilter}${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 team { 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 ...(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,\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 team: node.team?.key ?? null,\n labels: node.labels.nodes.map(label => label.name),\n createdAt: node.createdAt,\n updatedAt: node.updatedAt,\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 ({ 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(accessToken: string, idOrIdentifier: string): 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 team { 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,\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 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 /**\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 hooks: ctx.hooks,\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\nfunction linearIssueToIntakeIssue(issue: LinearIssue): IntakeIssue {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: null,\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":";AAcA,SAAS,wBAAwB;;;ACGjC,SAAS,kBAAkB;AAC3B,SAAS,SAAS;;;ACmIX,IAAM,4BAAN,cAAwC,MAAM;AAAA,EACnD,cAAc;AACZ,UAAM,+EAA+E;AAAA,EACvF;AACF;;;AF/HA,IAAM,UAAU;AAGhB,SAAS,MAAM,GAA0B;AACvC,SAAO;AACT;AA8CA,eAAe,iBACb,GACA,MACiF;AACjF,QAAM,KAAK,WAAW,CAAC;AACvB,QAAM,SAAS,KAAK,OAAO,CAAC;AAC5B,MAAI,CAAC,OAAQ,QAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;AACvE,MAAI,CAAC,OAAO,OAAO;AACjB,WAAO;AAAA,MACL,UAAU,EAAE;AAAA,QACV;AAAA,UACE,OAAO;AAAA,UACP,SAAS;AAAA,QACX;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,QAAQ,EAAE,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,EAAE;AAClE;AAOA,SAAS,iBAAiB,KAAoD;AAC5E,MAAI,QAAQ,UAAa,QAAQ,GAAI,QAAO;AAC5C,MAAI,IAAI,SAAS,OAAO,CAAC,gBAAgB,KAAK,GAAG,EAAG,QAAO;AAC3D,SAAO;AACT;AAGA,SAAS,iBAAiB,GAAiB,KAAc;AACvD,MAAI,eAAe,6BAA8B,IAA4B,WAAW,KAAK;AAC3F,WAAO,EAAE,KAAK,EAAE,OAAO,0BAA0B,SAAS,IAAI,0BAA0B,EAAE,QAAQ,GAAG,GAAG;AAAA,EAC1G;AACA,SAAO,EAAE,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CAAC;AACD,gBAAM,eAAe,OAAO,IAAI,YAAU;AAAA,YACxC,IAAI,MAAM;AAAA,YACV,YAAY,MAAM;AAAA,YAClB,OAAO,MAAM;AAAA,YACb,KAAK,MAAM;AAAA,YACX,OAAO,MAAM,SAAS;AAAA,YACtB,WAAW,MAAM,aAAa;AAAA,YAC9B,eAAe,MAAM,YAAY;AAAA,YACjC,UAAU,MAAM;AAAA,YAChB,MAAM,MAAM;AAAA,YACZ,QAAQ,MAAM;AAAA,YACd,WAAW,MAAM;AAAA,YACjB,WAAW,MAAM;AAAA,UACnB,EAAE;AACF,cAAI,oBAAoB,QAAQ,OAAO,oBAAoB;AACzD,kBAAM,QAAQ,MAAM,mBAAmB;AAAA,cACrC,OAAO,SAAS,OAAO;AAAA,cACvB,QAAQ,SAAS,OAAO;AAAA,cACxB;AAAA,cACA,QAAQ;AAAA,YACV,CAAC;AAAA,UACH;AACA,iBAAO,EAAE,KAAK,EAAE,QAAQ,cAAc,WAAW,CAAC;AAAA,QACpD,SAAS,KAAK;AACZ,iBAAO,iBAAiB,MAAM,CAAC,GAAG,GAAG;AAAA,QACvC;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/integrations/linear/routes.ts","../../../src/integrations/linear/agent-tools.ts","../../../src/integrations/linear/integration.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 type { RouteAuth } from '../../routes/route.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.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 ingestFactoryIssues?: (input: LinearRulesIngress) => Promise<unknown>;\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 > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Linear read failure to the API response for the SPA. */\nfunction linearFetchError(c: RouteContext, err: unknown) {\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 active issues (cursor-paged) ───────────────────\n // Respects the caller'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({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n integrationIds: ['linear'],\n });\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 projects selected means nothing is synced — don't fan out to Linear.\n const projectIds = selection.sourceIds ?? [];\n if (projectIds.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: projectIds,\n cursor: after,\n });\n const issuePayload = issues.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 team: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }));\n if (factoryProjectId && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n","/**\n * Linear tools exposed to the coding agent.\n *\n * Wired into the agent through the SDK's async `extraTools` provider: on each\n * tool-set resolution we map the session's resourceId (the factory project id)\n * to its owning org and only expose the Linear tools when that org has a\n * Linear connection. Projects whose org never connected Linear (or when the\n * feature is disabled) see no Linear tools at all — the model is never shown\n * tools it can't use.\n *\n * Tenancy mirrors the Linear API routes: everything is scoped by the org that\n * owns the project, and tokens are refreshed through the integration's shared\n * connection lifecycle.\n */\n\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\nfunction createLinearGetIssueTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_get_issue',\n description:\n \"Fetch a Linear issue's full details — title, description, state, assignee, labels, priority, and discussion comments. Use this whenever you're working on a Linear issue (e.g. ENG-123) to get its complete context.\",\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n }),\n execute: async ({ issue }: { issue: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to fetch issues.' };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const detail = await linear.intake.getIssue({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n });\n if (!detail) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return detail;\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to fetch Linear issue: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearCommentTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_create_comment',\n description:\n 'Post a comment on a Linear issue (e.g. to report investigation findings, link a PR, or ask a clarifying question). The comment is posted as the connected Linear integration, so make clear it comes from the agent.',\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n body: z.string().min(1).describe('The comment body, as Linear-flavored markdown.'),\n }),\n execute: async ({ issue, body }: { issue: string; body: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to post comments.' };\n }\n if (!linear.canPostComments(connection)) {\n return {\n error: 'The Linear connection does not have comment permissions. Reconnect Linear in Settings to grant them.',\n };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const comment = await linear.intake.createComment({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n body,\n });\n if (!comment) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return { posted: true, url: comment.url };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to post Linear comment: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\n/**\n * Async `extraTools` provider: expose Linear tools only when the session's\n * project belongs to an org with an active Linear connection.\n */\nexport async function buildLinearAgentTools({\n requestContext,\n linear,\n}: {\n requestContext: RequestContext;\n /** The integration instance providing the Linear API client. */\n linear: LinearIntegration;\n}): Promise<Record<string, ReturnType<typeof createLinearGetIssueTool> | ReturnType<typeof createLinearCommentTool>>> {\n if (!linear.authEnabled) return {};\n\n const ctx = requestContext.get('controller') as AgentControllerRequestContext | undefined;\n const resourceId = ctx?.resourceId;\n if (!resourceId) return {};\n\n const orgId = await linear.resolveOrgId(resourceId);\n if (!orgId) return {};\n const check = await linear.checkConnection(orgId);\n if (!check.connected) return {};\n\n return {\n linear_get_issue: createLinearGetIssueTool(linear, orgId),\n // Only offered when the granted OAuth scope allows posting comments —\n // connections made before `comments:create` was requested are read-only\n // until the org reconnects Linear.\n ...(check.canComment ? { linear_create_comment: createLinearCommentTool(linear, orgId) } : {}),\n };\n}\n","/**\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 type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\n\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 { buildLinearAgentTools } from './agent-tools.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 for the Linear OAuth application. All fields are required. */\nexport interface LinearIntegrationConfig {\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;\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 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\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;\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 };\n assignee: { name: string } | null;\n team: { 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 };\n assignee: { name: string } | null;\n team: { 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 = await this.listProjects(accessToken);\n return projects.map(project => ({\n id: project.id,\n name: project.name,\n type: 'project',\n }));\n },\n listItems: async ({ orgId, sourceIds, 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.listActiveIssues(accessToken, cursor, sourceIds);\n return {\n items: page.issues.map(issue => ({\n source: { type: 'issue', externalId: issue.id, url: issue.url },\n sourceId: issue.projectId,\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.priorityLabel,\n team: issue.team,\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 constructor(config: LinearIntegrationConfig) {\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 const result = await this.listActiveIssues(accessToken, input.cursor, input.sourceIds, input.labels);\n return {\n issues: result.issues.map(issue => linearIssueToIntakeIssue(issue)),\n nextCursor: result.nextCursor,\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 /**\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.\n */\n async listActiveIssues(\n accessToken: string,\n after?: string,\n projectIds?: string[],\n labels?: 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 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}${labelVar}) {\n issues(\n first: $first\n after: $after\n orderBy: updatedAt\n filter: { state: { type: { in: [\"triage\", \"backlog\", \"unstarted\", \"started\"] } }${projectFilter}${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 team { 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 ...(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,\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 team: node.team?.key ?? null,\n labels: node.labels.nodes.map(label => label.name),\n createdAt: node.createdAt,\n updatedAt: node.updatedAt,\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 ({ 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(accessToken: string, idOrIdentifier: string): 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 team { 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,\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 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 /**\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 ingestFactoryIssues: attachLinearRules(ctx),\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\nfunction linearIssueToIntakeIssue(issue: LinearIssue): IntakeIssue {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: null,\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":";AAcA,SAAS,wBAAwB;;;ACGjC,SAAS,kBAAkB;AAC3B,SAAS,SAAS;;;ACoIX,IAAM,4BAAN,cAAwC,MAAM;AAAA,EACnD,cAAc;AACZ,UAAM,+EAA+E;AAAA,EACvF;AACF;;;AFhIA,IAAM,UAAU;AAGhB,SAAS,MAAM,GAA0B;AACvC,SAAO;AACT;AA8CA,eAAe,iBACb,GACA,MACiF;AACjF,QAAM,KAAK,WAAW,CAAC;AACvB,QAAM,SAAS,KAAK,OAAO,CAAC;AAC5B,MAAI,CAAC,OAAQ,QAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;AACvE,MAAI,CAAC,OAAO,OAAO;AACjB,WAAO;AAAA,MACL,UAAU,EAAE;AAAA,QACV;AAAA,UACE,OAAO;AAAA,UACP,SAAS;AAAA,QACX;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,QAAQ,EAAE,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,EAAE;AAClE;AAOA,SAAS,iBAAiB,KAAoD;AAC5E,MAAI,QAAQ,UAAa,QAAQ,GAAI,QAAO;AAC5C,MAAI,IAAI,SAAS,OAAO,CAAC,gBAAgB,KAAK,GAAG,EAAG,QAAO;AAC3D,SAAO;AACT;AAGA,SAAS,iBAAiB,GAAiB,KAAc;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BAAoB,UAAU;AAC/D,gBAAM,EAAE,QAAQ,WAAW,IAAI,MAAM,OAAO,OAAO,WAAW;AAAA,YAC5D,YAAY,EAAE,MAAM,SAAS,YAAY;AAAA,YACzC,WAAW;AAAA,YACX,QAAQ;AAAA,UACV,CAAC;AACD,gBAAM,eAAe,OAAO,IAAI,YAAU;AAAA,YACxC,IAAI,MAAM;AAAA,YACV,YAAY,MAAM;AAAA,YAClB,OAAO,MAAM;AAAA,YACb,KAAK,MAAM;AAAA,YACX,OAAO,MAAM,SAAS;AAAA,YACtB,WAAW,MAAM,aAAa;AAAA,YAC9B,eAAe,MAAM,YAAY;AAAA,YACjC,UAAU,MAAM;AAAA,YAChB,MAAM,MAAM;AAAA,YACZ,QAAQ,MAAM;AAAA,YACd,WAAW,MAAM;AAAA,YACjB,WAAW,MAAM;AAAA,UACnB,EAAE;AACF,cAAI,oBAAoB,QAAQ,qBAAqB;AACnD,kBAAM,QAAQ,oBAAoB;AAAA,cAChC,OAAO,SAAS,OAAO;AAAA,cACvB,QAAQ,SAAS,OAAO;AAAA,cACxB;AAAA,cACA,QAAQ;AAAA,YACV,CAAC;AAAA,UACH;AACA,iBAAO,EAAE,KAAK,EAAE,QAAQ,cAAc,WAAW,CAAC;AAAA,QACpD,SAAS,KAAK;AACZ,iBAAO,iBAAiB,MAAM,CAAC,GAAG,GAAG;AAAA,QACvC;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { FactoryRules } from '../../rules/types.js';
|
|
2
|
+
import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
|
|
3
|
+
import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
|
|
4
|
+
import type { IntegrationContext } from '../base.js';
|
|
5
|
+
export interface LinearIssueIngress {
|
|
6
|
+
id: string;
|
|
7
|
+
identifier: string;
|
|
8
|
+
title: string;
|
|
9
|
+
url: string;
|
|
10
|
+
state: string;
|
|
11
|
+
stateType: string;
|
|
12
|
+
priorityLabel: string;
|
|
13
|
+
assignee: string | null;
|
|
14
|
+
team: string | null;
|
|
15
|
+
labels: string[];
|
|
16
|
+
createdAt: string;
|
|
17
|
+
updatedAt: string;
|
|
18
|
+
}
|
|
19
|
+
export interface LinearRulesOptions {
|
|
20
|
+
projects: Pick<FactoryProjectsStorage, 'get'>;
|
|
21
|
+
storage: WorkItemsStorage;
|
|
22
|
+
rules: FactoryRules;
|
|
23
|
+
}
|
|
24
|
+
export interface LinearRulesIngress {
|
|
25
|
+
orgId: string;
|
|
26
|
+
userId: string;
|
|
27
|
+
factoryProjectId: string;
|
|
28
|
+
issues: LinearIssueIngress[];
|
|
29
|
+
}
|
|
30
|
+
type IngressStatus = 'committed' | 'replayed' | 'missing';
|
|
31
|
+
export declare class LinearRules {
|
|
32
|
+
#private;
|
|
33
|
+
private readonly options;
|
|
34
|
+
constructor(options: LinearRulesOptions);
|
|
35
|
+
ingest(input: LinearRulesIngress): Promise<{
|
|
36
|
+
status: IngressStatus;
|
|
37
|
+
ingested: number;
|
|
38
|
+
}>;
|
|
39
|
+
}
|
|
40
|
+
export declare function attachLinearRules(context: IntegrationContext): ((input: LinearRulesIngress) => Promise<unknown>) | undefined;
|
|
41
|
+
export {};
|
|
42
|
+
//# sourceMappingURL=rules.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/rules.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAiD,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAExG,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAe,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAC9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAkBrD,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,C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246
|
-
// src/
|
|
246
|
+
// src/integrations/linear/rules.ts
|
|
247
247
|
var RULE_TIMEOUT_MS = 5e3;
|
|
248
248
|
async function withRuleTimeout(promise) {
|
|
249
249
|
let timeout;
|
|
@@ -258,7 +258,7 @@ async function withRuleTimeout(promise) {
|
|
|
258
258
|
if (timeout) clearTimeout(timeout);
|
|
259
259
|
}
|
|
260
260
|
}
|
|
261
|
-
var
|
|
261
|
+
var LinearRules = class {
|
|
262
262
|
constructor(options) {
|
|
263
263
|
this.options = options;
|
|
264
264
|
}
|
|
@@ -337,7 +337,17 @@ var FactoryLinearIssueService = class {
|
|
|
337
337
|
return committed.status;
|
|
338
338
|
}
|
|
339
339
|
};
|
|
340
|
+
function attachLinearRules(context) {
|
|
341
|
+
if (!context.rules) return void 0;
|
|
342
|
+
const rules = new LinearRules({
|
|
343
|
+
projects: context.storage.projects,
|
|
344
|
+
storage: context.rules.workItems,
|
|
345
|
+
rules: context.rules.config
|
|
346
|
+
});
|
|
347
|
+
return (input) => rules.ingest(input);
|
|
348
|
+
}
|
|
340
349
|
export {
|
|
341
|
-
|
|
350
|
+
LinearRules,
|
|
351
|
+
attachLinearRules
|
|
342
352
|
};
|
|
343
|
-
//# sourceMappingURL=
|
|
353
|
+
//# sourceMappingURL=rules.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/rules/resolve.ts","../../../src/rules/types.ts","../../../src/rules/validation.ts","../../../src/integrations/linear/rules.ts"],"sourcesContent":["import type {\n FactoryGithubEventName,\n FactoryGithubRuleLeaf,\n FactoryLinearEventName,\n FactoryLinearRuleLeaf,\n FactoryRuleBoard,\n FactoryRuleHandler,\n FactoryRuleSource,\n FactoryRuleStage,\n FactoryRules,\n FactoryStageRuleContext,\n FactoryToolResultRuleContext,\n FactoryToolRuleLeaf,\n} from './types.js';\n\nexport interface ResolvedFactoryStageRule {\n phase: 'exit' | 'enter';\n handler: FactoryRuleHandler<FactoryStageRuleContext>;\n}\n\nexport function resolveFactoryStageRules(\n rules: FactoryRules,\n input: {\n board: FactoryRuleBoard;\n source: FactoryRuleSource;\n fromStage: FactoryRuleStage;\n toStage: FactoryRuleStage;\n initialEntry?: boolean;\n },\n): ResolvedFactoryStageRule[] {\n if (input.fromStage === input.toStage && !input.initialEntry) return [];\n const boardRules = rules[input.board];\n const resolved: ResolvedFactoryStageRule[] = [];\n const onExit = input.initialEntry ? undefined : boardRules[input.fromStage]?.[input.source]?.onExit;\n if (onExit) resolved.push({ phase: 'exit', handler: onExit });\n const onEnter = boardRules[input.toStage]?.[input.source]?.onEnter;\n if (onEnter) resolved.push({ phase: 'enter', handler: onEnter });\n return resolved;\n}\n\nexport function resolveFactoryToolRule(rules: FactoryRules, toolName: string): FactoryToolRuleLeaf['onResult'] {\n return rules.tools[toolName]?.onResult;\n}\n\nexport function resolveFactoryGithubRule(\n rules: FactoryRules,\n event: FactoryGithubEventName,\n): FactoryGithubRuleLeaf['onEvent'] {\n return rules.github[event]?.onEvent;\n}\n\nexport function resolveFactoryLinearRule(\n rules: FactoryRules,\n event: FactoryLinearEventName,\n): FactoryLinearRuleLeaf['onEvent'] {\n return rules.linear[event]?.onEvent;\n}\n\nexport type ResolvedFactoryToolRule = FactoryRuleHandler<FactoryToolResultRuleContext>;\n","export type WorkItemSource = 'github-issue' | 'github-pr' | 'linear-issue' | 'manual';\n\nexport const FACTORY_RULE_STAGES = ['intake', 'triage', 'planning', 'execute', 'review', 'done', 'canceled'] as const;\nexport type FactoryRuleStage = (typeof FACTORY_RULE_STAGES)[number];\n\nexport const FACTORY_RULE_BOARDS = ['work', 'review'] as const;\nexport type FactoryRuleBoard = (typeof FACTORY_RULE_BOARDS)[number];\n\nexport const FACTORY_RULE_SOURCES = ['issue', 'pullRequest', 'linearIssue', 'manual'] as const;\nexport type FactoryRuleSource = (typeof FACTORY_RULE_SOURCES)[number];\n\nexport const FACTORY_GITHUB_EVENTS = [\n 'issueOpened',\n 'pullRequestOpened',\n 'pullRequestUpdated',\n 'pullRequestReviewRequested',\n 'pullRequestMerged',\n] as const;\nexport type FactoryGithubEventName = (typeof FACTORY_GITHUB_EVENTS)[number];\n\nexport const FACTORY_LINEAR_EVENTS = ['issueObserved'] as const;\nexport type FactoryLinearEventName = (typeof FACTORY_LINEAR_EVENTS)[number];\n\nexport type FactoryRuleJsonValue =\n | null\n | boolean\n | number\n | string\n | FactoryRuleJsonValue[]\n | { [key: string]: FactoryRuleJsonValue };\n\nexport interface FactoryRuleItemContext {\n id: string;\n source: WorkItemSource;\n sourceKey: string | null;\n parentWorkItemId: string | null;\n title: string;\n url: string | null;\n stages: readonly string[];\n}\n\nexport type FactoryRuleActor =\n | { type: 'human'; id: string }\n | { type: 'agent'; bindingId: string; role: string }\n | { type: 'github'; login: string; trusted: boolean; factoryAuthored: boolean }\n | { type: 'system'; id: string };\n\nexport interface FactoryRuleIngressIdentity {\n type: 'human' | 'agent' | 'toolResult' | 'github' | 'linear' | 'rule';\n id: string;\n}\n\nexport interface FactoryRuleCausalEntry {\n ingressId: string;\n decisionType: FactoryCommitDecision['type'];\n}\n\nexport interface FactoryRuleContextBase {\n tenant: { orgId: string; projectId: string };\n actor: FactoryRuleActor;\n ingress: FactoryRuleIngressIdentity;\n cause: string;\n causalChain: readonly FactoryRuleCausalEntry[];\n ruleSetVersion: string;\n}\n\nexport interface FactoryBoundRuleContext extends FactoryRuleContextBase {\n item: FactoryRuleItemContext;\n board: FactoryRuleBoard;\n itemRevision: number;\n}\n\nexport interface FactoryStageRuleContext extends FactoryBoundRuleContext {\n source: FactoryRuleSource;\n stage: FactoryRuleStage;\n fromStage: FactoryRuleStage;\n toStage: FactoryRuleStage;\n}\n\nexport interface FactoryToolResultRuleContext extends FactoryBoundRuleContext {\n toolName: string;\n threadId: string;\n assistantMessageId: string;\n toolCallId: string;\n result: {\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n };\n}\n\nexport interface FactoryGithubRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryGithubEventName;\n deliveryId: string;\n factory: { createdAt: string };\n repository: { id: number; fullName: string };\n issue?: { number: number; title: string; url: string; createdAt?: string };\n pullRequest?: {\n number: number;\n title: string;\n url: string;\n createdAt?: string;\n state: 'open' | 'closed';\n merged: boolean;\n headBranch: string;\n baseBranch: string;\n };\n}\n\nexport interface FactoryLinearRuleContext extends FactoryRuleContextBase {\n item?: FactoryRuleItemContext;\n board?: FactoryRuleBoard;\n itemRevision?: number;\n event: FactoryLinearEventName;\n issue: {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n team: string | null;\n labels: readonly string[];\n createdAt: string;\n updatedAt: string;\n };\n}\n\nexport type FactoryRuleHandler<TContext> = (\n context: Readonly<TContext>,\n) => FactoryRuleDecision | void | Promise<FactoryRuleDecision | void>;\n\nexport interface FactoryBoardRuleLeaf {\n onEnter?: FactoryRuleHandler<FactoryStageRuleContext>;\n onExit?: FactoryRuleHandler<FactoryStageRuleContext>;\n}\n\nexport interface FactoryToolRuleLeaf {\n onResult?: FactoryRuleHandler<FactoryToolResultRuleContext>;\n}\n\nexport interface FactoryGithubRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryGithubRuleContext>;\n}\n\nexport interface FactoryLinearRuleLeaf {\n onEvent?: FactoryRuleHandler<FactoryLinearRuleContext>;\n}\n\nexport type FactoryBoardRules = Partial<\n Record<FactoryRuleStage, Partial<Record<FactoryRuleSource, FactoryBoardRuleLeaf>>>\n>;\n\nexport interface FactoryRules {\n version: string;\n work: FactoryBoardRules;\n review: FactoryBoardRules;\n tools: Record<string, FactoryToolRuleLeaf>;\n github: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport interface FactoryRulesOverrides {\n work?: FactoryBoardRules;\n review?: FactoryBoardRules;\n tools?: Record<string, FactoryToolRuleLeaf>;\n github?: Partial<Record<FactoryGithubEventName, FactoryGithubRuleLeaf>>;\n linear?: Partial<Record<FactoryLinearEventName, FactoryLinearRuleLeaf>>;\n}\n\nexport type FactoryRuleRejectionCode =\n | 'forbidden'\n | 'invalid_transition'\n | 'missing_binding'\n | 'stale'\n | 'timeout'\n | 'rule_error'\n | 'causal_depth_exceeded'\n | 'repeated_transition';\n\nexport interface FactoryRuleRejectDecision {\n type: 'reject';\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\ninterface FactoryCommitDecisionBase {\n idempotencyKey: string;\n}\n\nexport interface FactoryTransitionDecision extends FactoryCommitDecisionBase {\n type: 'transition';\n board: FactoryRuleBoard;\n stage: FactoryRuleStage;\n}\n\nexport interface FactoryUpsertLinkedWorkItemDecision extends FactoryCommitDecisionBase {\n type: 'upsertLinkedWorkItem';\n board: FactoryRuleBoard;\n source: WorkItemSource;\n sourceKey: string;\n title: string;\n url: string | null;\n stage: FactoryRuleStage;\n metadata?: Record<string, FactoryRuleJsonValue>;\n}\n\nexport interface FactoryInvokeSkillDecision extends FactoryCommitDecisionBase {\n type: 'invokeSkill';\n role: string;\n skillName: string;\n arguments?: string;\n precedingMessage?: string;\n}\n\nexport interface FactorySendMessageDecision extends FactoryCommitDecisionBase {\n type: 'sendMessage';\n role: string;\n message: string;\n priority?: 'medium' | 'high' | 'urgent';\n idleBehavior?: 'persist' | 'wake';\n prepareBinding?: boolean;\n}\n\nexport interface FactoryNotifyDecision extends FactoryCommitDecisionBase {\n type: 'notify';\n title: string;\n body?: string;\n level?: 'info' | 'warning' | 'error';\n}\n\nexport type FactoryCommitDecision =\n | FactoryTransitionDecision\n | FactoryUpsertLinkedWorkItemDecision\n | FactoryInvokeSkillDecision\n | FactorySendMessageDecision\n | FactoryNotifyDecision;\n\nexport type FactoryRuleDecision = FactoryRuleRejectDecision | FactoryCommitDecision;\n\nexport interface FactoryTransitionResultAccepted {\n status: 'accepted';\n transitionId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n decisions: FactoryCommitDecision[];\n}\n\nexport interface FactoryTransitionResultRejected {\n status: 'rejected';\n transitionId: string;\n itemId: string;\n code: FactoryRuleRejectionCode;\n reason: string;\n}\n\nexport type FactoryTransitionResult = FactoryTransitionResultAccepted | FactoryTransitionResultRejected;\n\nexport function factoryRuleSourceForWorkItem(source: WorkItemSource): FactoryRuleSource {\n switch (source) {\n case 'github-issue':\n return 'issue';\n case 'github-pr':\n return 'pullRequest';\n case 'linear-issue':\n return 'linearIssue';\n case 'manual':\n return 'manual';\n }\n}\n","import {\n FACTORY_GITHUB_EVENTS,\n FACTORY_LINEAR_EVENTS,\n FACTORY_RULE_BOARDS,\n FACTORY_RULE_SOURCES,\n FACTORY_RULE_STAGES,\n} from './types.js';\nimport type {\n FactoryBoardRules,\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRules,\n FactoryRuleRejectionCode,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nconst MAX_ROLE_LENGTH = 32;\nconst MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nconst IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nconst SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = ['github-issue', 'github-pr', 'linear-issue', 'manual'];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nfunction validateBoardRules(rules: unknown, label: string): asserts rules is FactoryBoardRules {\n if (!isPlainObject(rules)) throw new FactoryRuleValidationError(`${label} must be an object.`);\n for (const [stage, sources] of Object.entries(rules)) {\n enumValue(stage, FACTORY_RULE_STAGES, `${label} stage`);\n if (!isPlainObject(sources)) throw new FactoryRuleValidationError(`${label}.${stage} must be an object.`);\n for (const [source, leaf] of Object.entries(sources)) {\n enumValue(source, FACTORY_RULE_SOURCES, `${label}.${stage} source`);\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`${label}.${stage}.${source} must be an object.`);\n assertExactKeys(leaf, ['onEnter', 'onExit'], `${label}.${stage}.${source}`);\n for (const handler of Object.values(leaf)) {\n if (handler !== undefined && typeof handler !== 'function') {\n throw new FactoryRuleValidationError(`${label}.${stage}.${source} handlers must be functions.`);\n }\n }\n }\n }\n}\n\nexport function assertFactoryRules(rules: unknown): asserts rules is FactoryRules {\n if (!isPlainObject(rules)) throw new FactoryRuleValidationError('Factory rules must be an object.');\n assertExactKeys(rules, ['version', 'work', 'review', 'tools', 'github', 'linear'], 'Factory rules');\n boundedString(rules.version, 'Factory rule version', MAX_VERSION_LENGTH);\n validateBoardRules(rules.work, 'Factory rules.work');\n validateBoardRules(rules.review, 'Factory rules.review');\n\n if (!isPlainObject(rules.tools)) throw new FactoryRuleValidationError('Factory rules.tools must be an object.');\n for (const [toolName, leaf] of Object.entries(rules.tools)) {\n boundedString(toolName, 'Factory tool name', 128, IDENTIFIER_RE);\n if (!isPlainObject(leaf))\n throw new FactoryRuleValidationError(`Factory rules.tools.${toolName} must be an object.`);\n assertExactKeys(leaf, ['onResult'], `Factory rules.tools.${toolName}`);\n if (leaf.onResult !== undefined && typeof leaf.onResult !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.tools.${toolName}.onResult must be a function.`);\n }\n }\n\n if (!isPlainObject(rules.github)) throw new FactoryRuleValidationError('Factory rules.github must be an object.');\n for (const [event, leaf] of Object.entries(rules.github)) {\n enumValue(event, FACTORY_GITHUB_EVENTS, 'Factory GitHub event');\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`Factory rules.github.${event} must be an object.`);\n assertExactKeys(leaf, ['onEvent'], `Factory rules.github.${event}`);\n if (leaf.onEvent !== undefined && typeof leaf.onEvent !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.github.${event}.onEvent must be a function.`);\n }\n }\n\n if (!isPlainObject(rules.linear)) throw new FactoryRuleValidationError('Factory rules.linear must be an object.');\n for (const [event, leaf] of Object.entries(rules.linear)) {\n enumValue(event, FACTORY_LINEAR_EVENTS, 'Factory Linear event');\n if (!isPlainObject(leaf)) throw new FactoryRuleValidationError(`Factory rules.linear.${event} must be an object.`);\n assertExactKeys(leaf, ['onEvent'], `Factory rules.linear.${event}`);\n if (leaf.onEvent !== undefined && typeof leaf.onEvent !== 'function') {\n throw new FactoryRuleValidationError(`Factory rules.linear.${event}.onEvent must be a function.`);\n }\n }\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'board', 'stage'], 'Factory transition decision');\n return {\n type,\n ...commonCommitFields(value),\n board: enumValue(value.board, FACTORY_RULE_BOARDS, 'Factory transition board'),\n stage: enumValue(value.stage, FACTORY_RULE_STAGES, 'Factory transition stage'),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'source', 'sourceKey', 'title', 'url', 'stage', 'metadata'],\n 'Factory linked work item decision',\n );\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n return {\n type,\n ...commonCommitFields(value),\n board: enumValue(value.board, FACTORY_RULE_BOARDS, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n url,\n stage: enumValue(value.stage, FACTORY_RULE_STAGES, 'Factory linked work item stage'),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'skillName', 'arguments', 'precedingMessage'],\n 'Factory invoke skill decision',\n );\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n","import { resolveFactoryLinearRule } from '../../rules/resolve.js';\nimport type { FactoryLinearRuleContext, FactoryRuleDecision, FactoryRules } from '../../rules/types.js';\nimport { validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { WorkItemRow, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nexport interface LinearIssueIngress {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface LinearRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n rules: FactoryRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\nexport class LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\n\n async ingest(input: LinearRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n\n const items = await this.options.storage.list({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n statuses.push(await this.#ingestIssue(input, issue, itemsBySourceKey.get(`linear:${issue.identifier}`)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: WorkItemRow | undefined,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: 'linear.issueObserved',\n causalChain: [],\n ruleSetVersion: this.options.rules.version,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n },\n board: 'work' as const,\n itemRevision: relatedItem.revision,\n }\n : {}),\n event: 'issueObserved',\n issue,\n };\n\n const rule = resolveFactoryLinearRule(this.options.rules, context.event);\n let decision: FactoryRuleDecision | void;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => ({ ...entry }));\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Linear rule failed.',\n };\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: 'linear.issueObserved' },\n ruleSetVersion: this.options.rules.version,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n return committed.status;\n }\n}\n\nexport function attachLinearRules(\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.rules) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.rules.workItems,\n rules: context.rules.config,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";AAmDO,SAAS,yBACd,OACA,OACkC;AAClC,SAAO,MAAM,OAAO,KAAK,GAAG;AAC9B;;;ACtDO,IAAM,sBAAsB,CAAC,UAAU,UAAU,YAAY,WAAW,UAAU,QAAQ,UAAU;AAGpG,IAAM,sBAAsB,CAAC,QAAQ,QAAQ;;;ACY7C,IAAM,gCAAgC;AAG7C,IAAM,6BAA6B;AACnC,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AACzB,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAC7B,IAAM,kBAAkB;AACxB,IAAM,wBAAwB;AAC9B,IAAM,wBAAwB;AAC9B,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;AACjC,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;AAEjC,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AACzB,IAAM,oBAA+C,CAAC,gBAAgB,aAAa,gBAAgB,QAAQ;AAC3G,IAAM,kBAAuD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EAC3C,OAAO;AAAA,EAEhB,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,cAAc,OAAkD;AACvE,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,EAAG,QAAO;AAChF,QAAM,YAAY,OAAO,eAAe,KAAK;AAC7C,SAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,gBAAgB,OAAgC,MAAyB,OAAqB;AACrG,QAAM,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AG,MAAM,EAAE;AAAA,MAClF;AAAA,IACF,SAAS,OAAO;AACd,YAAM,WAAW,iBAAiB,SAAS,MAAM,YAAY;AAC7D,gBAAU;AAAA,QACR,QAAQ;AAAA,QACR,MAAM,WAAW,YAAY;AAAA,QAC7B,QAAQ,WACJ,uCACA,iBAAiB,QACf,MAAM,QAAQ,MAAM,GAAG,GAAK,IAC5B;AAAA,MACR;AAAA,IACF;AAEA,UAAM,YAAY,MAAM,KAAK,QAAQ,QAAQ,qBAAqB;AAAA,MAChE,OAAO,MAAM;AAAA,MACb,kBAAkB,MAAM;AAAA,MACxB,YAAY,aAAa,MAAM;AAAA,MAC/B,SAAS,EAAE,UAAU,WAAW,aAAa,uBAAuB;AAAA,MACpE,gBAAgB,KAAK,QAAQ,MAAM;AAAA,MACnC,kBAAkB,aAAa,YAAY;AAAA,MAC3C;AAAA,MACA;AAAA,MACA;AAAA,MACA,aAAa,CAAC;AAAA,MACd,KAAK,oBAAI,KAAK;AAAA,IAChB,CAAC;AACD,WAAO,UAAU;AAAA,EACnB;AACF;AAEO,SAAS,kBACd,SAC+D;AAC/D,MAAI,CAAC,QAAQ,MAAO,QAAO;AAC3B,QAAM,QAAQ,IAAI,YAAY;AAAA,IAC5B,UAAU,QAAQ,QAAQ;AAAA,IAC1B,SAAS,QAAQ,MAAM;AAAA,IACvB,OAAO,QAAQ,MAAM;AAAA,EACvB,CAAC;AACD,SAAO,WAAS,MAAM,OAAO,KAAK;AACpC;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,KAAK,EAEV,MAAM,EAIP,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAuBV,cAAc,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