{ "$schema": "https://ui.shadcn.com/schema/registry-item.json", "name": "linear", "type": "registry:item", "title": "Linear", "description": "Editable Linear ingestion with nine independent raw resource streams, overlapping update windows, and complete issue history.", "dependencies": [ "@chkit/core@^0.2.0-beta.12", "@chkit/plugin-ingest@^0.2.0-beta.12", "zod@^4.3.6" ], "devDependencies": [ "@types/bun@^1.2.0" ], "files": [ { "path": "linear/README.md", "type": "registry:file", "target": "src/integrations/linear/README.md", "content": "# Linear raw ingestion example\n\nOne workspace pipeline syncs nine independent resource streams into native JSON tables. Readers preserve provider fields and relationship IDs; joins, business mappings, and derived metrics belong in ClickHouse. Issue labels are the explicitly selected exception: their complete names are stored as strings on each issue.\n\nSet `LINEAR_API_KEY` in the runtime environment and configure a direct ClickHouse connection. `config.ts` passes it as `apiKey`; set `apiKey` there to use another key. Edit the GraphQL queries and raw table declarations in `sources/` to request fields and configure destinations. Native JSON requires ClickHouse 25.3 or later.\n\n`config.ts` supplies source identity, initial timestamp, overlap, and the API key. `createLinearPipeline(config)` snapshots configuration; each reader validates it with zod when its stream runs, so invalid settings or a missing key fail that stream before any request. `client.ts` sends authenticated GraphQL requests through the ingestion runtime and validates connections. `pipeline.ts` groups resources without dependency ordering. Destination schemas stay in their source modules rather than runtime configuration.\n\nKeep stream IDs and destinations tied to one Linear workspace. The reader does not resolve the authenticated workspace identity: changing the token to another workspace requires a new source ID and destinations before ingestion, so old checkpoints cannot skip its history. Adding requested fields later requires reconciliation to populate older observations.\n\n```sh\nbunx chkit check\nbunx chkit generate --name add_linear\n# Review the migration before applying it.\nbunx chkit migrate --apply\nbunx chkit ingest run --tag provider:linear\n```\n\n## Resources\n\n| Stream suffix | Raw table | Selection |\n| --- | --- | --- |\n| `issues` | `linear_issues_raw` | Updated-time window |\n| `comments` | `linear_comments_raw` | Own updated-time window |\n| `projects` | `linear_projects_raw` | Updated-time window |\n| `project_updates` | `linear_project_updates_raw` | Own updated-time window |\n| `cycles` | `linear_cycles_raw` | Updated-time window |\n| `users` | `linear_users_raw` | Updated-time window, including disabled users |\n| `teams` | `linear_teams_raw` | Updated-time window |\n| `issue_relations` | `linear_issue_relations_raw` | Full accessible relation collection |\n| `issue_history` | `linear_issue_history_raw` | All accessible history after independent issue discovery |\n\nThe default IDs are `linear` for the pipeline and `linear.` for each stream. Each owns its journal progress. Run a resource separately with:\n\n```sh\nbunx chkit ingest run --tag provider:linear --tag resource:comments\nbunx chkit ingest run --tag provider:linear --tag resource:issue_history\n```\n\nRepeated tags use AND matching. The default `maxStreams: 1` executes selected streams sequentially to limit API usage. Selection and failure in one stream do not make another stream's discovery depend on it. Give expensive history reads their own schedule and execution budget; individual issues remain records inside the resource stream.\n\n## Stored data and joins\n\nEach table uses the provider record ID as its row identity and stores requested fields in the native ClickHouse JSON column `raw`. This is not an exact JSON archive: native JSON normalization can omit explicit null properties and empty objects. See [native JSON storage fidelity](https://chkit.obsessiondb.com/api-sync/destinations/). Relationships remain provider-shaped references such as `project: { id }`, `cycle: { id }`, or `issue: { id }`. Join those IDs to other raw tables in ClickHouse.\n\nIssues contain metadata, state details, relationship IDs, and a fully paginated `labels` string array. Comments, project updates, relations, and history are individual records in their own tables. Comments request nullable parent IDs and user references, including comments on project updates or other parent types; explicit null properties may be absent in stored JSON. Issue history retains native transition fields and its issue reference; cycle movement and status-duration calculations happen downstream.\n\nWorkflow state, project status, and label definition streams are outside this package's current scope. Project/team memberships and other paginated associations are not fetched as truncated nested collections. Bounded inline state/status metadata remains raw.\n\n## Sync and recovery\n\nSeven root collections use bounded `updatedAt` filters, `orderBy: updatedAt`, and `includeArchived: true`. Users also request `includeDisabled: true`. Each initial window starts at the configured date, defaulting to the Unix epoch. Subsequent windows replay five minutes before that stream's committed watermark. Comments use their own collection and update timestamp; a comment on an old issue does not require the issue stream to run or its parent timestamp to change.\n\nRelay cursors only continue the current read. `paginate()` owns request retries and rejects repeated continuations; readers validate connections, identities, timestamps, and GraphQL errors, including partial responses. Issues complete all label pages before publishing their label strings. A label retrieval failure leaves only the issues window incomplete.\n\nNewest-first pages do not define a safe timestamp frontier. A window checkpoint advances to its upper cutoff only after all pages and destination writes succeed, including an empty successful window. An interrupted or failed window replays from its lower bound. Mutable row chunks omit explicit immutable IDs so changed provider fields stay eligible on replay.\n\nIssue relations have a root listing without a reliable timestamp filter. Issue history has no workspace-level feed or timestamp filter: its reader independently paginates every accessible issue ID, then each issue's history. Both use the library's `fullSync()` completion checkpoints. Each invocation starts its collection again, and interrupted work replays from the beginning. Their successful completion is journaled even when empty; no parent stream watermark, saved mutable offset, or per-issue scan ledger is used. Full-sync resources ignore date bounds and provide no date-range backfill.\n\nThe API does not guarantee atomic snapshots. Deleted records and removed relations remain stored; missing observations do not generate tombstones. A label rename is not assumed to update every issue's timestamp. Periodic reconciliation refreshes older observations and changes beyond overlap:\n\n```sh\nbunx chkit ingest run --tag provider:linear --tag resource:issues --backfill reconcile-2026-10-05 --from 1970-01-01\nbunx chkit ingest status --tag provider:linear --json\n```\n\nUse a new backfill ID for each reconciliation. Timestamp replay reads current observations, while the separate history stream reads the provider's accessible event records; neither reconstructs an atomic historical workspace snapshot. Run one ingestion process per ClickHouse target at a time.\n\n## Upgrading existing data\n\nVersion `0.2.0` adds eight raw destinations and keeps issue row IDs and the default `linear.issues` stream ID stable. Published `0.1.0` installations may retain nested comment payloads in issue JSON. Those observations are neither removed nor moved automatically: populate the new destinations through their own initial reads and reconcile or deliberately migrate legacy data. Application queries should join the comments table; old embedded fields can remain until their issue is observed again or migrated.\n\n## Fixture tests\n\n```sh\nbunx chkit add linear --with-tests\nbun test src/integrations/linear/tests/basic.test.ts\n```\n\nPortable fixtures exercise independent selection and checkpoints, raw fields and join IDs, complete label names, old-parent comment and history coverage, continuation validation, retries, source/sink failure replay, mutable full reads, and empty completion without live credentials.\n" }, { "path": "linear/index.ts", "type": "registry:file", "target": "src/integrations/linear/index.ts", "content": "export { linearPipeline, createLinearPipeline } from './pipeline.js'\nexport { linear_issuesRaw } from './sources/issues.js'\nexport { linear_commentsRaw } from './sources/comments.js'\nexport { linear_projectsRaw } from './sources/projects.js'\nexport { linear_projectUpdatesRaw } from './sources/project-updates.js'\nexport { linear_cyclesRaw } from './sources/cycles.js'\nexport { linear_usersRaw } from './sources/users.js'\nexport { linear_teamsRaw } from './sources/teams.js'\nexport { linear_issueRelationsRaw } from './sources/issue-relations.js'\nexport { linear_issueHistoryRaw } from './sources/issue-history.js'\n" }, { "path": "linear/config.ts", "type": "registry:file", "target": "src/integrations/linear/config.ts", "content": "import { z } from 'zod'\n\nconst missingKey = 'Set LINEAR_API_KEY or pass apiKey.'\nconst apiKey = z.string().optional().pipe(z.string({ error: missingKey }).trim().min(1, missingKey))\n\nexport const linearConfigSchema = z.object({\n /** Stable, non-secret stream prefix for this installation. */\n sourceId: z.string().refine((value) => value.trim() !== '', 'must not be blank'),\n start: z.date(),\n overlapMs: z.int().nonnegative(),\n /** Linear API key; read when a stream runs, never by schema commands. */\n apiKey,\n})\n\nexport type LinearConfig = z.input\n\n// Source identity and date selection; raw destinations and requested fields live in sources/.\nexport const linearConfig: LinearConfig = {\n sourceId: 'linear',\n start: new Date(0),\n overlapMs: 5 * 60 * 1000,\n apiKey: process.env.LINEAR_API_KEY,\n}\n" }, { "path": "linear/client.ts", "type": "registry:file", "target": "src/integrations/linear/client.ts", "content": "import { HttpError, paginate, type Page, type SourceContext, type TimestampRange } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { linearConfigSchema, type LinearConfig } from './config.js'\n\nexport type LinearNode = z.infer\nexport type LinearSettings = Omit, 'apiKey'>\n\nexport interface ConnectionRequest {\n query: string\n path: readonly string[]\n label: string\n variables?: Record\n initial?: string\n window?: TimestampRange\n}\n\nexport interface LinearClient {\n settings: LinearSettings\n connection(request: ConnectionRequest): AsyncGenerator>\n inline(value: unknown, label: string): Page\n}\n\ninterface GraphqlReply {\n body: unknown\n response: Response\n}\n\nconst nonBlank = z.string().refine((value) => value.trim() !== '', 'must not be blank')\nconst linearNode = z.looseObject({ id: nonBlank })\nconst linearObject = z.looseObject({})\nconst connection = z.looseObject({\n nodes: z.array(linearNode),\n pageInfo: z.looseObject({ hasNextPage: z.boolean(), endCursor: z.string().nullish() }),\n})\nconst windowedNode = z.looseObject({ updatedAt: z.string().refine((value) => Number.isFinite(Date.parse(value)), 'must be a timestamp') })\nconst graphqlErrors = z.looseObject({ errors: z.array(z.unknown()).min(1) })\nconst graphqlResponse = z.looseObject({\n data: linearObject.nullish(),\n errors: z.array(z.looseObject({ extensions: z.looseObject({ code: z.unknown() }).nullish() })).optional(),\n})\n\nexport function createLinearClient(context: SourceContext, config: LinearConfig): LinearClient {\n const { apiKey, ...settings } = linearConfigSchema.parse(config)\n const graphql = async (query: string, variables: Record) => {\n const reply = await post(context, apiKey, JSON.stringify({ query, variables }))\n return graphqlData(reply)\n }\n return {\n settings,\n connection: (request) => paginate({\n context, initial: request.initial, label: `POST /graphql ${request.label}`,\n fetchPage: async (after) => {\n const data = await graphql(request.query, { ...request.variables, after: after ?? null })\n const page = linearConnection(request.path.reduce((value, field) => linearObject.parse(value)[field], data), request.label)\n if (request.window) assertWindow(page.items, request.window, request.label)\n return page\n },\n }),\n inline: linearConnection,\n }\n}\n\nasync function post(context: SourceContext, apiKey: string, body: string): Promise {\n try {\n const response = await context.fetch('https://api.linear.app/graphql', {\n method: 'POST', redirect: 'error', body,\n headers: { Authorization: apiKey, 'Content-Type': 'application/json' },\n })\n return { body: await response.json(), response }\n } catch (error) {\n if (!(error instanceof HttpError)) throw error\n if (error.status === 429) throw rateLimited(error.response, error.body)\n if (error.status !== 400) throw error\n const reply: unknown = await error.response.json().catch(() => undefined)\n if (!graphqlErrors.safeParse(reply).success) throw error\n return { body: reply, response: error.response }\n }\n}\n\nasync function graphqlData(reply: GraphqlReply): Promise> {\n const { data, errors } = graphqlResponse.parse(reply.body)\n if (errors?.some((error) => error.extensions?.code === 'RATELIMITED')) {\n throw rateLimited(reply.response, JSON.stringify(reply.body))\n }\n if (errors?.length) throw new Error(`Linear GraphQL returned errors: ${JSON.stringify(errors)}`)\n if (!data) throw new Error('Linear GraphQL returned no data.')\n return data\n}\n\n/** Linear puts the wait in per-budget reset headers (epoch milliseconds). */\nfunction rateLimited(response: Response, body: string): HttpError {\n const resets = ['requests', 'endpoint-requests', 'complexity'].flatMap((kind) => {\n if (response.headers.get(`x-ratelimit-${kind}-remaining`) !== '0') return []\n const reset = Number(response.headers.get(`x-ratelimit-${kind}-reset`))\n return Number.isFinite(reset) && reset > 0 ? [Math.max(0, reset - Date.now())] : []\n })\n return HttpError.withStatus(response, 429, { body, retryAfterMs: resets.length ? Math.max(...resets) : undefined })\n}\n\nfunction linearConnection(value: unknown, label: string): Page {\n const { nodes, pageInfo } = connection.parse(value)\n if (!pageInfo.hasNextPage) return { items: nodes, next: undefined }\n if (!pageInfo.endCursor?.trim()) throw new Error(`Linear ${label} returned no new cursor.`)\n return { items: nodes, next: pageInfo.endCursor }\n}\n\nfunction assertWindow(items: readonly LinearNode[], window: TimestampRange, label: string): void {\n for (const item of items) {\n const updated = Date.parse(windowedNode.parse(item).updatedAt)\n if (updated < window.from.getTime() || updated > window.to.getTime()) {\n throw new Error(`Linear ${label} has no updatedAt within the requested window.`)\n }\n }\n}\n" }, { "path": "linear/pipeline.ts", "type": "registry:file", "target": "src/integrations/linear/pipeline.ts", "content": "import { definePipeline, defineStream, fullSync, timestampWindow } from '@chkit/plugin-ingest'\n\nimport { linearConfig, type LinearConfig } from './config.js'\nimport { linear_issuesRaw, readIssues } from './sources/issues.js'\nimport { linear_commentsRaw, readComments } from './sources/comments.js'\nimport { linear_projectsRaw, readProjects } from './sources/projects.js'\nimport { linear_projectUpdatesRaw, readProjectUpdates } from './sources/project-updates.js'\nimport { linear_cyclesRaw, readCycles } from './sources/cycles.js'\nimport { linear_usersRaw, readUsers } from './sources/users.js'\nimport { linear_teamsRaw, readTeams } from './sources/teams.js'\nimport { linear_issueRelationsRaw, readIssueRelations } from './sources/issue-relations.js'\nimport { linear_issueHistoryRaw, readIssueHistory } from './sources/issue-history.js'\n\nexport function createLinearPipeline(config: LinearConfig = linearConfig) {\n const source = { ...config, start: new Date(config.start) }\n return definePipeline({\n id: source.sourceId, tags: ['provider:linear'], maxStreams: 1, maxFetches: 1,\n streams: [\n defineStream({\n id: `${source.sourceId}.issues`, tags: ['resource:issues'], destination: linear_issuesRaw,\n incremental: timestampWindow({ start: source.start, overlapMs: source.overlapMs }),\n read: (context) => readIssues(context, source),\n }),\n defineStream({\n id: `${source.sourceId}.comments`, tags: ['resource:comments'], destination: linear_commentsRaw,\n incremental: timestampWindow({ start: source.start, overlapMs: source.overlapMs }),\n read: (context) => readComments(context, source),\n }),\n defineStream({\n id: `${source.sourceId}.projects`, tags: ['resource:projects'], destination: linear_projectsRaw,\n incremental: timestampWindow({ start: source.start, overlapMs: source.overlapMs }),\n read: (context) => readProjects(context, source),\n }),\n defineStream({\n id: `${source.sourceId}.project_updates`, tags: ['resource:project_updates'], destination: linear_projectUpdatesRaw,\n incremental: timestampWindow({ start: source.start, overlapMs: source.overlapMs }),\n read: (context) => readProjectUpdates(context, source),\n }),\n defineStream({\n id: `${source.sourceId}.cycles`, tags: ['resource:cycles'], destination: linear_cyclesRaw,\n incremental: timestampWindow({ start: source.start, overlapMs: source.overlapMs }),\n read: (context) => readCycles(context, source),\n }),\n defineStream({\n id: `${source.sourceId}.users`, tags: ['resource:users'], destination: linear_usersRaw,\n incremental: timestampWindow({ start: source.start, overlapMs: source.overlapMs }),\n read: (context) => readUsers(context, source),\n }),\n defineStream({\n id: `${source.sourceId}.teams`, tags: ['resource:teams'], destination: linear_teamsRaw,\n incremental: timestampWindow({ start: source.start, overlapMs: source.overlapMs }),\n read: (context) => readTeams(context, source),\n }),\n defineStream({\n id: `${source.sourceId}.issue_relations`, tags: ['resource:issue_relations'], destination: linear_issueRelationsRaw,\n incremental: fullSync(),\n read: (context) => readIssueRelations(context, source),\n }),\n defineStream({\n id: `${source.sourceId}.issue_history`, tags: ['resource:issue_history'], destination: linear_issueHistoryRaw,\n incremental: fullSync(),\n read: (context) => readIssueHistory(context, source),\n }),\n ],\n })\n}\n\nexport const linearPipeline = createLinearPipeline()\n" }, { "path": "linear/sources/issues.ts", "type": "registry:file", "target": "src/integrations/linear/sources/issues.ts", "content": "import { rawRows, rawTable, type ReadContext, type TimestampRange, type TimestampWindowState } from '@chkit/plugin-ingest'\nimport { z } from 'zod'\n\nimport { createLinearClient, type LinearClient, type LinearNode } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst query = `query Issues($after: String, $from: DateTimeOrDuration!, $to: DateTimeOrDuration!) {\n issues(first: 100, after: $after, includeArchived: true, orderBy: updatedAt,\n filter: { updatedAt: { gte: $from, lte: $to } }) {\n nodes { id identifier number title description url branchName createdAt updatedAt archivedAt\n startedAt completedAt canceledAt dueDate estimate priority sortOrder subIssueSortOrder\n team { id } state { id name type color } assignee { id } creator { id }\n project { id } cycle { id } parent { id }\n labels(first: 20, includeArchived: true) { nodes { id name } pageInfo { hasNextPage endCursor } }\n }\n pageInfo { hasNextPage endCursor }\n }\n}`\nconst labelsQuery = `query IssueLabels($id: String!, $after: String) {\n issue(id: $id) { labels(first: 100, after: $after, includeArchived: true) {\n nodes { id name } pageInfo { hasNextPage endCursor }\n } }\n}`\n\nconst labelNode = z.looseObject({ name: z.string().refine((value) => value.trim() !== '', 'must not be blank') })\n\nexport const linear_issuesRaw = rawTable({ database: 'default', name: 'linear_issues_raw' })\n\nexport async function* readIssues(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const page of client.connection({\n query, path: ['issues'], label: 'issues', window: context.selection,\n variables: { from: context.selection.from.toISOString(), to: context.selection.to.toISOString() },\n })) {\n for (const issue of page.items) {\n const labels = await completeLabels(client, issue)\n yield { rows: rawRows([{ ...issue, labels }], linearId) }\n }\n }\n}\n\n/** Label names are the explicitly requested projection; consume every label page first. */\nasync function completeLabels(client: LinearClient, issue: LinearNode): Promise {\n const first = client.inline(issue.labels, 'issue labels')\n const labels = first.items.map(labelName)\n if (first.next !== undefined) {\n for await (const page of client.connection({\n query: labelsQuery, path: ['issue', 'labels'], variables: { id: linearId(issue) }, initial: first.next, label: 'issue labels',\n })) labels.push(...page.items.map(labelName))\n }\n return labels\n}\n\nfunction labelName(label: LinearNode): string {\n return labelNode.parse(label).name\n}\n" }, { "path": "linear/sources/common.ts", "type": "registry:file", "target": "src/integrations/linear/sources/common.ts", "content": "import type { LinearNode } from '../client.js'\n\nexport function linearId(item: LinearNode): string {\n return item.id\n}\n" }, { "path": "linear/sources/comments.ts", "type": "registry:file", "target": "src/integrations/linear/sources/comments.ts", "content": "import { rawRows, rawTable, type ReadContext, type TimestampRange, type TimestampWindowState } from '@chkit/plugin-ingest'\n\nimport { createLinearClient } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst query = `query Comments($after: String, $from: DateTimeOrDuration!, $to: DateTimeOrDuration!) {\n comments(first: 100, after: $after, includeArchived: true, orderBy: updatedAt,\n filter: { updatedAt: { gte: $from, lte: $to } }) {\n nodes { id body url createdAt updatedAt archivedAt editedAt resolvedAt quotedText reactionData\n issueId projectUpdateId documentContentId initiativeUpdateId projectId initiativeId\n parentId resolvingCommentId user { id } externalUser { id } resolvingUser { id }\n }\n pageInfo { hasNextPage endCursor }\n }\n}`\n\nexport const linear_commentsRaw = rawTable({ database: 'default', name: 'linear_comments_raw' })\n\nexport async function* readComments(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const page of client.connection({\n query, path: ['comments'], label: 'comments', window: context.selection,\n variables: { from: context.selection.from.toISOString(), to: context.selection.to.toISOString() },\n })) yield { rows: rawRows(page.items, linearId) }\n}\n" }, { "path": "linear/sources/projects.ts", "type": "registry:file", "target": "src/integrations/linear/sources/projects.ts", "content": "import { rawRows, rawTable, type ReadContext, type TimestampRange, type TimestampWindowState } from '@chkit/plugin-ingest'\n\nimport { createLinearClient } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst query = `query Projects($after: String, $from: DateTimeOrDuration!, $to: DateTimeOrDuration!) {\n projects(first: 100, after: $after, includeArchived: true, orderBy: updatedAt,\n filter: { updatedAt: { gte: $from, lte: $to } }) {\n nodes { id name description content url slugId icon color createdAt updatedAt archivedAt\n startDate startDateResolution targetDate targetDateResolution startedAt completedAt canceledAt\n priority sortOrder lead { id } creator { id } status { id name type color }\n }\n pageInfo { hasNextPage endCursor }\n }\n}`\n\nexport const linear_projectsRaw = rawTable({ database: 'default', name: 'linear_projects_raw' })\n\nexport async function* readProjects(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const page of client.connection({\n query, path: ['projects'], label: 'projects', window: context.selection,\n variables: { from: context.selection.from.toISOString(), to: context.selection.to.toISOString() },\n })) yield { rows: rawRows(page.items, linearId) }\n}\n" }, { "path": "linear/sources/project-updates.ts", "type": "registry:file", "target": "src/integrations/linear/sources/project-updates.ts", "content": "import { rawRows, rawTable, type ReadContext, type TimestampRange, type TimestampWindowState } from '@chkit/plugin-ingest'\n\nimport { createLinearClient } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst query = `query ProjectUpdates($after: String, $from: DateTimeOrDuration!, $to: DateTimeOrDuration!) {\n projectUpdates(first: 100, after: $after, includeArchived: true, orderBy: updatedAt,\n filter: { updatedAt: { gte: $from, lte: $to } }) {\n nodes { id body url slugId health createdAt updatedAt archivedAt editedAt reactionData\n project { id } user { id }\n }\n pageInfo { hasNextPage endCursor }\n }\n}`\n\nexport const linear_projectUpdatesRaw = rawTable({ database: 'default', name: 'linear_project_updates_raw' })\n\nexport async function* readProjectUpdates(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const page of client.connection({\n query, path: ['projectUpdates'], label: 'project updates', window: context.selection,\n variables: { from: context.selection.from.toISOString(), to: context.selection.to.toISOString() },\n })) yield { rows: rawRows(page.items, linearId) }\n}\n" }, { "path": "linear/sources/cycles.ts", "type": "registry:file", "target": "src/integrations/linear/sources/cycles.ts", "content": "import { rawRows, rawTable, type ReadContext, type TimestampRange, type TimestampWindowState } from '@chkit/plugin-ingest'\n\nimport { createLinearClient } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst query = `query Cycles($after: String, $from: DateTimeOrDuration!, $to: DateTimeOrDuration!) {\n cycles(first: 100, after: $after, includeArchived: true, orderBy: updatedAt,\n filter: { updatedAt: { gte: $from, lte: $to } }) {\n nodes { id number name description startsAt endsAt completedAt autoArchivedAt\n createdAt updatedAt archivedAt team { id }\n }\n pageInfo { hasNextPage endCursor }\n }\n}`\n\nexport const linear_cyclesRaw = rawTable({ database: 'default', name: 'linear_cycles_raw' })\n\nexport async function* readCycles(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const page of client.connection({\n query, path: ['cycles'], label: 'cycles', window: context.selection,\n variables: { from: context.selection.from.toISOString(), to: context.selection.to.toISOString() },\n })) yield { rows: rawRows(page.items, linearId) }\n}\n" }, { "path": "linear/sources/users.ts", "type": "registry:file", "target": "src/integrations/linear/sources/users.ts", "content": "import { rawRows, rawTable, type ReadContext, type TimestampRange, type TimestampWindowState } from '@chkit/plugin-ingest'\n\nimport { createLinearClient } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst query = `query Users($after: String, $from: DateTimeOrDuration!, $to: DateTimeOrDuration!) {\n users(first: 100, after: $after, includeArchived: true, includeDisabled: true, orderBy: updatedAt,\n filter: { updatedAt: { gte: $from, lte: $to } }) {\n nodes { id name displayName email description title avatarUrl url timezone\n active admin owner guest app disableReason createdAt updatedAt archivedAt organization { id }\n }\n pageInfo { hasNextPage endCursor }\n }\n}`\n\nexport const linear_usersRaw = rawTable({ database: 'default', name: 'linear_users_raw' })\n\nexport async function* readUsers(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const page of client.connection({\n query, path: ['users'], label: 'users', window: context.selection,\n variables: { from: context.selection.from.toISOString(), to: context.selection.to.toISOString() },\n })) yield { rows: rawRows(page.items, linearId) }\n}\n" }, { "path": "linear/sources/teams.ts", "type": "registry:file", "target": "src/integrations/linear/sources/teams.ts", "content": "import { rawRows, rawTable, type ReadContext, type TimestampRange, type TimestampWindowState } from '@chkit/plugin-ingest'\n\nimport { createLinearClient } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst query = `query Teams($after: String, $from: DateTimeOrDuration!, $to: DateTimeOrDuration!) {\n teams(first: 100, after: $after, includeArchived: true, orderBy: updatedAt,\n filter: { updatedAt: { gte: $from, lte: $to } }) {\n nodes { id name key description icon color timezone visibility retiredAt\n cyclesEnabled cycleStartDay cycleDuration cycleCooldownTime createdAt updatedAt archivedAt\n parent { id } organization { id }\n }\n pageInfo { hasNextPage endCursor }\n }\n}`\n\nexport const linear_teamsRaw = rawTable({ database: 'default', name: 'linear_teams_raw' })\n\nexport async function* readTeams(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const page of client.connection({\n query, path: ['teams'], label: 'teams', window: context.selection,\n variables: { from: context.selection.from.toISOString(), to: context.selection.to.toISOString() },\n })) yield { rows: rawRows(page.items, linearId) }\n}\n" }, { "path": "linear/sources/issue-relations.ts", "type": "registry:file", "target": "src/integrations/linear/sources/issue-relations.ts", "content": "import { rawRows, rawTable, type ReadContext } from '@chkit/plugin-ingest'\n\nimport { createLinearClient } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst query = `query IssueRelations($after: String) {\n issueRelations(first: 100, after: $after, includeArchived: true, orderBy: updatedAt) {\n nodes { id type createdAt updatedAt archivedAt issue { id } relatedIssue { id } }\n pageInfo { hasNextPage endCursor }\n }\n}`\n\nexport const linear_issueRelationsRaw = rawTable({ database: 'default', name: 'linear_issue_relations_raw' })\n\nexport async function* readIssueRelations(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const page of client.connection({\n query, path: ['issueRelations'], label: 'issue relations',\n })) yield { rows: rawRows(page.items, linearId) }\n}\n" }, { "path": "linear/sources/issue-history.ts", "type": "registry:file", "target": "src/integrations/linear/sources/issue-history.ts", "content": "import { rawRows, rawTable, type ReadContext } from '@chkit/plugin-ingest'\n\nimport { createLinearClient } from '../client.js'\nimport type { LinearConfig } from '../config.js'\nimport { linearId } from './common.js'\n\nconst parentsQuery = `query IssueHistoryParents($after: String) {\n issues(first: 100, after: $after, includeArchived: true, orderBy: updatedAt) {\n nodes { id } pageInfo { hasNextPage endCursor }\n }\n}`\nconst historyQuery = `query IssueHistory($id: String!, $after: String) {\n issue(id: $id) { history(first: 100, after: $after, includeArchived: true, orderBy: updatedAt) {\n nodes { id createdAt updatedAt archivedAt issue { id } actorId\n fromTitle toTitle updatedDescription fromAssigneeId toAssigneeId\n fromPriority toPriority fromEstimate toEstimate fromDueDate toDueDate\n fromTeamId toTeamId fromParentId toParentId fromStateId toStateId\n fromCycleId toCycleId fromProjectId toProjectId toConvertedProjectId\n addedLabelIds removedLabelIds archived trashed autoClosed autoArchived attachmentId\n fromSlaStartedAt toSlaStartedAt fromSlaBreachesAt toSlaBreachesAt\n fromSlaBreached toSlaBreached fromSlaType toSlaType\n }\n pageInfo { hasNextPage endCursor }\n } }\n}`\n\nexport const linear_issueHistoryRaw = rawTable({ database: 'default', name: 'linear_issue_history_raw' })\n\n/** Own complete parent discovery: old issues can gain history independently of other streams. */\nexport async function* readIssueHistory(context: ReadContext, config: LinearConfig) {\n const client = createLinearClient(context, config)\n for await (const parents of client.connection({\n query: parentsQuery, path: ['issues'], label: 'history parents',\n })) {\n for (const issue of parents.items) {\n for await (const page of client.connection({\n query: historyQuery, path: ['issue', 'history'], variables: { id: linearId(issue) }, label: 'issue history',\n })) yield { rows: rawRows(page.items, linearId) }\n }\n }\n}\n" }, { "path": "linear/tests/basic.test.ts", "type": "registry:file", "target": "src/integrations/linear/tests/basic.test.ts", "role": "test", "content": "import { expect, test } from 'bun:test'\nimport { runIngestion, selectStreams } from '@chkit/plugin-ingest'\nimport { createMemoryDestination, createMemoryJournal } from '@chkit/plugin-ingest/testing'\n\nimport { createLinearPipeline, linearPipeline } from '../index.js'\nimport { linearConfig, type LinearConfig } from '../config.js'\n\nconst fixtureConfig = { ...linearConfig, apiKey: 'fixture' }\nconst cutoff = new Date('2026-01-02T00:00:00Z')\nconst oneRetry = { retries: 1, minTimeout: 0, maxTimeout: 0 }\nconst updatedAt = '2026-01-01T12:00:00Z'\nconst resources = ['issues', 'comments', 'projects', 'project_updates', 'cycles', 'users', 'teams', 'issue_relations', 'issue_history']\nconst timestampResources = resources.slice(0, 7)\nconst issue = { id: 'issue-a', identifier: 'ENG-1', title: 'Archived issue', updatedAt, archivedAt: updatedAt,\n team: { id: 'team-a' }, assignee: { id: 'user-a' }, project: { id: 'project-a' }, cycle: { id: 'cycle-a' },\n custom: { retained: true }, labels: connection([{ id: 'label-a', name: 'Bug' }, { id: 'label-b', name: 'Customer' }]) }\nconst comment = { id: 'comment-a', body: 'Discussion', updatedAt, issueId: 'issue-a', projectUpdateId: null, user: { id: 'user-a' }, custom: ['retained'] }\nconst project = { id: 'project-a', name: 'Project', updatedAt, archivedAt: updatedAt, lead: { id: 'user-a' }, status: { id: 'status-a', name: 'Started' }, custom: true }\nconst projectUpdate = { id: 'project-update-a', body: 'Progress', updatedAt, project: { id: 'project-a' }, user: { id: 'user-a' }, custom: true }\nconst cycle = { id: 'cycle-a', number: 7, updatedAt, archivedAt: updatedAt, team: { id: 'team-a' }, custom: true }\nconst user = { id: 'user-a', name: 'Disabled user', updatedAt, active: false, organization: { id: 'organization-a' }, custom: true }\nconst team = { id: 'team-a', key: 'ENG', name: 'Archived team', updatedAt, archivedAt: updatedAt, custom: true }\nconst relation = { id: 'relation-a', type: 'blocks', updatedAt: '2020-01-01T00:00:00Z', issue: { id: 'issue-a' }, relatedIssue: { id: 'issue-b' }, custom: true }\nconst history = { id: 'history-a', updatedAt: '2020-01-01T00:00:00Z', issue: { id: 'issue-a' }, actorId: 'user-a', fromTitle: 'Before', toTitle: 'After', custom: true }\nconst expectedRows = {\n issues: { ...issue, labels: ['Bug', 'Customer'] }, comments: comment, projects: project, project_updates: projectUpdate,\n cycles: cycle, users: user, teams: team, issue_relations: relation, issue_history: history,\n}\n\ninterface GraphqlRequest { query: string; variables: Record }\ntype Responder = (body: GraphqlRequest) => Response | Promise\ntype Pipeline = ReturnType\n\ntest('Linear exposes nine independently selectable raw resource tables with provider join identities', async () => {\n const requests: GraphqlRequest[] = []\n const env = linearEnv((body) => { requests.push(body); return fixtureResponse(body) })\n const pipeline = fixturePipeline()\n expect(linearPipeline.streams).toHaveLength(9)\n expect(pipeline.streams.map((stream) => stream.id).sort()).toEqual(resources.map((resource) => `linear.${resource}`).sort())\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const result = await runIngestion(request(pipeline), { ...env, journal, destination, now: () => cutoff })\n expect(result.ok, JSON.stringify(result)).toBe(true)\n expect(destination.tables.size).toBe(9)\n for (const [resource, raw] of Object.entries(expectedRows)) {\n expect(destination.tables.get(`default.linear_${resource}_raw`)?.map(({ id, raw }) => ({ id, raw }))).toEqual([{ id: raw.id, raw }])\n }\n for (const body of requests) expect(body.query).toContain('includeArchived: true')\n expect(requests.find((body) => operation(body) === 'Users')?.query).toContain('includeDisabled: true')\n expect(requests.find((body) => operation(body) === 'Comments')?.query).toContain('issueId projectUpdateId')\n expect(requests.find((body) => operation(body) === 'IssueHistory')?.query).toContain('actorId')\n const bounded = requests.filter((body) => body.variables.from !== undefined)\n expect(bounded).toHaveLength(7)\n for (const body of bounded) {\n expect(body.query).toContain('updatedAt: { gte: $from, lte: $to }')\n expect(body.query).toContain('orderBy: updatedAt')\n expect(body.variables).toEqual({ after: null, from: '1970-01-01T00:00:00.000Z', to: cutoff.toISOString() })\n }\n for (const resource of timestampResources) {\n expect((await journal.readCheckpoint(`linear.${resource}`)).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n }\n for (const resource of ['issue_relations', 'issue_history']) {\n expect((await journal.readCheckpoint(`linear.${resource}`)).envelope).toBeUndefined()\n expect((await journal.readCheckpoint(`linear.${resource}`)).lastSuccessSeq).toBeGreaterThan(0)\n }\n})\n\ntest('each resource runs alone and reversing stream order preserves the same observations', async () => {\n const pipeline = fixturePipeline(), combined = createMemoryDestination()\n expect((await runIngestion(request({ ...pipeline, streams: [...pipeline.streams].reverse() }),\n { ...linearEnv(), journal: createMemoryJournal(), destination: combined, now: () => cutoff })).ok).toBe(true)\n for (const resource of resources) {\n const destination = createMemoryDestination(), calls: string[] = []\n const env = linearEnv((body) => { calls.push(operation(body)); return fixtureResponse(body) })\n const selected = request(pipeline, resource)\n expect(selected.selected.map((entry) => entry.stream.id)).toEqual([`linear.${resource}`])\n expect((await runIngestion(selected, { ...env, journal: createMemoryJournal(), destination, now: () => cutoff })).ok).toBe(true)\n expect(destination.tables.size).toBe(1)\n expect(destination.tables.get(`default.linear_${resource}_raw`)?.map(({ id, raw }) => ({ id, raw })))\n .toEqual(combined.tables.get(`default.linear_${resource}_raw`)?.map(({ id, raw }) => ({ id, raw })))\n expect(calls).toHaveLength(resource === 'issue_history' ? 2 : 1)\n }\n})\n\ntest('Linear page adapters preserve continuations and empty terminal pages', async () => {\n const afters: unknown[] = []\n const env = linearEnv((body) => {\n afters.push(body.variables.after)\n return response('comments', body.variables.after === 'next' ? [comment] : [],\n body.variables.after === null ? 'next' : body.variables.after === 'next' ? 'terminal' : null)\n })\n const destination = createMemoryDestination()\n const result = await runIngestion(request(fixturePipeline(), 'comments'), { ...env, journal: createMemoryJournal(), destination, now: () => cutoff })\n expect(result.streams.map((stream) => [stream.outcome, stream.chunks])).toEqual([['succeeded', 3]])\n expect(afters).toEqual([null, 'next', 'terminal'])\n expect(destination.tables.get('default.linear_comments_raw')?.map((row) => row.raw)).toEqual([comment])\n})\n\ntest('comment-only edits use their own update window without discovering or depending on old issues', async () => {\n let edited = false\n const requests: GraphqlRequest[] = []\n const oldIssue = { ...issue, updatedAt: '2020-01-01T00:00:00Z' }\n const env = linearEnv((body) => {\n requests.push(body)\n if (operation(body) === 'Issues') return response('issues', edited ? [] : [oldIssue])\n if (operation(body) === 'Comments') return response('comments', [{ ...comment,\n body: edited ? 'Edited discussion on an old issue' : 'Original discussion', updatedAt: edited ? '2026-01-02T12:00:00Z' : updatedAt }])\n throw new Error(`Unexpected request: ${operation(body)}`)\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const initial = { ...request(pipeline), selected: request(pipeline).selected.filter((entry) => ['linear.issues', 'linear.comments'].includes(entry.stream.id)) }\n expect((await runIngestion(initial, { ...env, journal, destination, now: () => cutoff })).ok).toBe(true)\n requests.length = 0\n edited = true\n expect((await runIngestion(request(pipeline, 'comments'), { ...env, journal, destination, now: () => new Date('2026-01-03') })).ok).toBe(true)\n expect(requests.map(operation)).toEqual(['Comments'])\n expect(requests[0]?.variables).toEqual({ after: null, from: '2026-01-01T23:55:00.000Z', to: '2026-01-03T00:00:00.000Z' })\n expect((await journal.readCheckpoint('linear.issues')).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n expect((await journal.readCheckpoint('linear.comments')).envelope?.state).toEqual({ watermark: '2026-01-03T00:00:00.000Z' })\n const rows = destination.tables.get('default.linear_comments_raw') ?? []\n expect(rows).toHaveLength(2)\n expect(new Set(rows.map((row) => row.id)).size).toBe(1)\n expect(rows.at(-1)?.raw).toEqual({ ...comment, body: 'Edited discussion on an old issue', updatedAt: '2026-01-02T12:00:00Z' })\n requests.length = 0\n expect((await runIngestion(request(pipeline, 'issues'), { ...env, journal, destination, now: () => new Date('2026-01-04') })).ok).toBe(true)\n expect(requests.map(operation)).toEqual(['Issues'])\n expect(requests[0]?.variables.from).toBe('2026-01-01T23:55:00.000Z')\n expect((await journal.readCheckpoint('linear.comments')).envelope?.state).toEqual({ watermark: '2026-01-03T00:00:00.000Z' })\n})\n\ntest('issue labels are complete string arrays across nested pages while issue pages remain independent', async () => {\n const requests: GraphqlRequest[] = []\n const nextIssue = { ...issue, id: 'issue-b', labels: connection([]) }\n const env = linearEnv((body) => {\n requests.push(body)\n if (operation(body) === 'IssueLabels') return Response.json({ data: { issue: { labels: connection(\n body.variables.after === 'labels-next' ? [{ id: 'label-b', name: 'Customer' }] : [{ id: 'label-c', name: 'Urgent' }],\n body.variables.after === 'labels-next' ? 'labels-last' : null) } } })\n if (body.variables.after) return response('issues', [nextIssue])\n return response('issues', [{ ...issue, labels: connection([{ id: 'label-a', name: 'Bug' }], 'labels-next') }], 'issues-next')\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n expect((await runIngestion(request(pipeline, 'issues'), { ...env, journal, destination, now: () => cutoff })).ok).toBe(true)\n expect(requests.map(operation)).toEqual(['Issues', 'IssueLabels', 'IssueLabels', 'Issues'])\n expect(requests.filter((body) => operation(body) === 'IssueLabels').map((body) => body.variables)).toEqual([\n { id: 'issue-a', after: 'labels-next' }, { id: 'issue-a', after: 'labels-last' },\n ])\n expect(requests.every((body) => !body.query.includes('comments('))).toBe(true)\n expect(destination.tables.get('default.linear_issues_raw')?.map((row) => row.raw)).toEqual([\n { ...issue, labels: ['Bug', 'Customer', 'Urgent'] }, { ...nextIssue, labels: [] },\n ])\n expect((await journal.readCheckpoint('linear.issues')).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n})\n\ntest('a labels page failure leaves the issue window uncommitted and replays from its first page', async () => {\n let fail = true\n const starts: unknown[] = []\n const env = linearEnv((body) => {\n if (operation(body) === 'IssueLabels') return fail ? Response.json({ errors: [{ message: 'denied' }] })\n : Response.json({ data: { issue: { labels: connection([{ id: 'label-b', name: 'Customer' }]) } } })\n starts.push(body.variables.after)\n return response('issues', [{ ...issue, labels: connection([{ id: 'label-a', name: 'Bug' }], 'labels-next') }])\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'issues')\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff })).ok).toBe(false)\n expect((await journal.readCheckpoint('linear.issues')).envelope).toBeUndefined()\n expect(destination.tables.size).toBe(0)\n fail = false\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff })).ok).toBe(true)\n expect(starts).toEqual([null, null])\n expect(destination.tables.get('default.linear_issues_raw')?.[0]?.raw).toEqual(expectedRows.issues)\n})\n\ntest('a failed comment page does not block any other resource and the next run replays its own window', async () => {\n let fail = true\n const starts: unknown[] = []\n const second = { ...comment, id: 'comment-b' }\n const env = linearEnv((body) => {\n if (operation(body) !== 'Comments') return fixtureResponse(body)\n if (body.variables.after) return fail ? new Response('denied', { status: 403 }) : response('comments', [second])\n starts.push(body.variables.after)\n return response('comments', [comment], 'comments-next')\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const failed = await runIngestion(request(pipeline), { ...env, journal, destination, now: () => cutoff })\n expect(failed.ok).toBe(false)\n expect(failed.streams.filter((stream) => stream.outcome === 'failed').map((stream) => stream.streamId)).toEqual(['linear.comments'])\n expect((await journal.readCheckpoint('linear.comments')).envelope).toBeUndefined()\n for (const resource of resources.filter((resource) => resource !== 'comments')) {\n expect((await journal.readCheckpoint(`linear.${resource}`)).lastSuccessSeq).toBeGreaterThan(0)\n }\n fail = false\n expect((await runIngestion(request(pipeline, 'comments'), { ...env, journal, destination, now: () => cutoff })).ok).toBe(true)\n expect(starts).toEqual([null, null])\n expect(destination.tables.get('default.linear_comments_raw')?.map((row) => row.id)).toEqual(['comment-a', 'comment-b'])\n expect((await journal.readCheckpoint('linear.comments')).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n})\n\ntest('rejected comment writes preserve their prior watermark and replay the unacknowledged update window', async () => {\n const starts: unknown[] = []\n const env = linearEnv((body) => {\n starts.push(body.variables.from)\n return response('comments', [{ ...comment, updatedAt: body.variables.from === '1970-01-01T00:00:00.000Z' ? updatedAt : '2026-01-02T12:00:00Z' }])\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'comments')\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff })).ok).toBe(true)\n const now = () => new Date('2026-01-03')\n expect((await runIngestion(selected, { ...env, journal, destination: { insert: async () => { throw new Error('sink rejected') } }, now })).ok).toBe(false)\n expect((await journal.readCheckpoint('linear.comments')).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n expect((await runIngestion(selected, { ...env, journal, destination, now })).ok).toBe(true)\n expect(starts).toEqual(['1970-01-01T00:00:00.000Z', '2026-01-01T23:55:00.000Z', '2026-01-01T23:55:00.000Z'])\n expect((await journal.readCheckpoint('linear.comments')).envelope?.state).toEqual({ watermark: now().toISOString() })\n})\n\ntest('empty resources complete independently and timestamp windows overlap while full resources enumerate again', async () => {\n const requests: GraphqlRequest[] = []\n const env = linearEnv((body) => { requests.push(body); return emptyResponse(body) })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n for (const now of [cutoff, new Date('2026-01-03')]) {\n expect((await runIngestion(request(pipeline), { ...env, journal, destination, now: () => now })).ok).toBe(true)\n }\n expect(destination.tables.size).toBe(0)\n for (const resource of timestampResources) {\n expect((await journal.readCheckpoint(`linear.${resource}`)).envelope?.state).toEqual({ watermark: '2026-01-03T00:00:00.000Z' })\n }\n const incremental = requests.filter((body) => body.variables.from !== undefined)\n expect(incremental).toHaveLength(14)\n expect(incremental.slice(0, 7).every((body) => body.variables.from === '1970-01-01T00:00:00.000Z')).toBe(true)\n expect(incremental.slice(7).every((body) => body.variables.from === '2026-01-01T23:55:00.000Z')).toBe(true)\n for (const name of ['IssueRelations', 'IssueHistoryParents']) {\n const full = requests.filter((body) => operation(body) === name)\n expect(full).toHaveLength(2)\n expect(full.every((body) => !body.query.includes('filter:') && body.variables.from === undefined)).toBe(true)\n }\n for (const resource of ['issue_relations', 'issue_history']) {\n expect((await journal.readCheckpoint(`linear.${resource}`)).envelope).toBeUndefined()\n expect(journal.events.filter((event) => event.namespaceId === `linear.${resource}` && event.eventKind === 'work_finished' && event.workState === 'succeeded')).toHaveLength(2)\n }\n})\n\ntest('history enumerates all old and archived issues independently and retains paginated history join identities', async () => {\n const requests: GraphqlRequest[] = []\n const second = { ...history, id: 'history-b', toTitle: 'Later' }\n const third = { ...history, id: 'history-c', issue: { id: 'issue-b' } }\n const env = linearEnv((body) => {\n requests.push(body)\n if (operation(body) === 'IssueHistoryParents') return response('issues', [{ id: body.variables.after ? 'issue-b' : 'issue-a',\n updatedAt: '2020-01-01T00:00:00Z', archivedAt: '2020-01-02T00:00:00Z' }], body.variables.after ? null : 'parents-next')\n return Response.json({ data: { issue: { history: connection(body.variables.id === 'issue-b' ? [third] : body.variables.after ? [second] : [history],\n body.variables.id === 'issue-a' && !body.variables.after ? 'history-next' : null) } } })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n expect((await runIngestion(request(pipeline, 'issue_history'), { ...env, journal, destination, now: () => cutoff })).ok).toBe(true)\n expect(requests.map(operation)).toEqual(['IssueHistoryParents', 'IssueHistory', 'IssueHistory', 'IssueHistoryParents', 'IssueHistory'])\n expect(requests.every((body) => body.variables.from === undefined && !body.query.includes('filter:'))).toBe(true)\n expect(destination.tables.get('default.linear_issue_history_raw')?.map(({ id, raw }) => ({ id, raw }))).toEqual([history, second, third].map((raw) => ({ id: raw.id, raw })))\n expect((await journal.readCheckpoint('linear.issues')).lastSuccessSeq).toBe(0)\n expect((await journal.readCheckpoint('linear.issue_history')).envelope).toBeUndefined()\n})\n\ntest('mutable relation full sync replays its first page after source and sink failures and refreshes old records', async () => {\n let fail = true, changed = false\n const starts: unknown[] = []\n const second = { ...relation, id: 'relation-b' }\n const env = linearEnv((body) => {\n expect(operation(body)).toBe('IssueRelations')\n expect(body.variables.from).toBeUndefined()\n expect(body.query).not.toContain('filter:')\n if (body.variables.after) return fail ? new Response('denied', { status: 403 }) : response('issueRelations', [second])\n starts.push(body.variables.after)\n return response('issueRelations', [{ ...relation, type: changed ? 'duplicate' : relation.type }], 'relations-next')\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'issue_relations')\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff })).ok).toBe(false)\n expect((await journal.readCheckpoint('linear.issue_relations')).lastSuccessSeq).toBe(0)\n fail = false\n expect((await runIngestion(selected, { ...env, journal, destination: { insert: async () => { throw new Error('sink rejected') } }, now: () => cutoff })).ok).toBe(false)\n expect((await journal.readCheckpoint('linear.issue_relations')).lastSuccessSeq).toBe(0)\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff })).ok).toBe(true)\n changed = true\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => new Date('2026-01-03') })).ok).toBe(true)\n expect(starts).toEqual([null, null, null, null])\n expect((await journal.readCheckpoint('linear.issue_relations')).envelope).toBeUndefined()\n const rows = destination.tables.get('default.linear_issue_relations_raw') ?? []\n expect(rows.filter((row) => row.id === relation.id).map((row) => row.raw)).toEqual([relation, { ...relation, type: 'duplicate' }])\n})\n\ntest('history failures replay all parent discovery without recording completion before every history write succeeds', async () => {\n let fail = true\n const starts: unknown[] = []\n const second = { ...history, id: 'history-b', issue: { id: 'issue-b' } }\n const env = linearEnv((body) => {\n if (operation(body) === 'IssueHistoryParents') {\n starts.push(body.variables.after)\n return response('issues', [{ id: 'issue-a' }, { id: 'issue-b' }])\n }\n if (body.variables.id === 'issue-b' && fail) return new Response('denied', { status: 403 })\n return Response.json({ data: { issue: { history: connection(body.variables.id === 'issue-a' ? [history] : [second]) } } })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination(), selected = request(pipeline, 'issue_history')\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff })).ok).toBe(false)\n expect((await journal.readCheckpoint('linear.issue_history')).lastSuccessSeq).toBe(0)\n expect((await journal.readCheckpoint('linear.issue_history')).envelope).toBeUndefined()\n fail = false\n expect((await runIngestion(selected, { ...env, journal, destination: { insert: async () => { throw new Error('sink rejected') } }, now: () => cutoff })).ok).toBe(false)\n expect((await journal.readCheckpoint('linear.issue_history')).lastSuccessSeq).toBe(0)\n expect((await runIngestion(selected, { ...env, journal, destination, now: () => cutoff })).ok).toBe(true)\n expect(starts).toEqual([null, null, null])\n expect((await journal.readCheckpoint('linear.issue_history')).envelope).toBeUndefined()\n expect((await journal.readCheckpoint('linear.issue_history')).lastSuccessSeq).toBeGreaterThan(0)\n expect(destination.tables.get('default.linear_issue_history_raw')?.map(({ id, raw }) => ({ id, raw }))).toEqual([history, second].map((raw) => ({ id: raw.id, raw })))\n expect((await journal.readCheckpoint('linear.issues')).lastSuccessSeq).toBe(0)\n})\n\ntest('Linear binds custom date selection and isolates each installation and resource checkpoint', async () => {\n const requests: GraphqlRequest[] = []\n const config = { ...fixtureConfig, sourceId: 'linear.fixture', start: new Date('2025-01-01'), overlapMs: 60_000, apiKey: 'bound-token' }\n const env = { fetch: async (_input: string | URL, init?: RequestInit) => {\n const authorization = new Headers(init?.headers).get('authorization')\n if (authorization === 'denied') return new Response('denied', { status: 403 })\n expect(authorization).toBe('bound-token')\n const body: GraphqlRequest = JSON.parse(String(init?.body))\n requests.push(body)\n return emptyResponse(body)\n } }\n const pipeline = createLinearPipeline(config)\n config.start.setUTCFullYear(2000)\n config.overlapMs = 3_600_000\n config.sourceId = 'mutated'\n config.apiKey = 'changed'\n expect(pipeline.streams.map((stream) => stream.id).sort()).toEqual(resources.map((resource) => `linear.fixture.${resource}`).sort())\n const failing = createLinearPipeline({ ...fixtureConfig, sourceId: 'linear.denied', apiKey: 'denied' })\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const selected = selectStreams([failing, pipeline], ['resource:comments'])\n const result = await runIngestion({ selected, backfill: undefined }, { ...env, retry: { retries: 0 }, journal, destination, now: () => cutoff })\n expect(result.streams.map((stream) => stream.outcome)).toEqual(['failed', 'succeeded'])\n expect(requests[0]?.variables).toEqual({ after: null, from: '2025-01-01T00:00:00.000Z', to: cutoff.toISOString() })\n expect((await journal.readCheckpoint('linear.denied.comments')).envelope).toBeUndefined()\n expect((await journal.readCheckpoint('linear.fixture.comments')).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n const onlyFixture = selectStreams([failing, pipeline], ['stream:linear.fixture.comments'])\n expect(onlyFixture.map((entry) => entry.stream.id)).toEqual(['linear.fixture.comments'])\n expect((await runIngestion({ selected: onlyFixture, backfill: undefined }, { ...env, journal, destination, now: () => new Date('2026-01-03') })).ok).toBe(true)\n expect(requests[1]?.variables.from).toBe('2026-01-01T23:59:00.000Z')\n expect((await journal.readCheckpoint('linear.fixture.issues')).envelope).toBeUndefined()\n expect((await journal.readCheckpoint('linear.comments')).envelope).toBeUndefined()\n})\n\ntest('nullable provider comment references retain the comment ID and unmodified raw payload', async () => {\n const detached = { ...comment, issueId: null, projectUpdateId: 'project-update-a', user: null }\n const env = linearEnv(() => response('comments', [detached]))\n const pipeline = fixturePipeline()\n const destination = createMemoryDestination()\n expect((await runIngestion(request(pipeline, 'comments'), { ...env, journal: createMemoryJournal(), destination, now: () => cutoff })).ok).toBe(true)\n expect(destination.tables.get('default.linear_comments_raw')?.map(({ id, raw }) => ({ id, raw }))).toEqual([{ id: detached.id, raw: detached }])\n})\n\ntest('GraphQL HTTP400 and HTTP200 rate exhaustion each consume exactly one page retry', async () => {\n for (const status of [400, 200]) {\n let attempts = 0\n const env = linearEnv(() => ++attempts === 1\n ? Response.json({ errors: [{ message: 'rate limit', extensions: { code: 'RATELIMITED' } }] }, { status, headers: { 'Retry-After': '0' } })\n : response('comments', []))\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal()\n expect((await runIngestion(request(pipeline, 'comments'), { ...env, retry: oneRetry, journal, destination: createMemoryDestination(), now: () => cutoff })).ok).toBe(true)\n expect(attempts).toBe(2)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled' && event.errorClass === 'rate_limited')).toHaveLength(1)\n }\n})\n\ntest('partial GraphQL data with errors cannot write rows, retry, or complete a resource', async () => {\n for (const resource of ['comments', 'issue_relations', 'issue_history']) {\n let attempts = 0\n const env = linearEnv((body) => {\n attempts++\n return Response.json({ data: operation(body) === 'IssueHistoryParents' ? { issues: connection([{ id: issue.id }]) }\n : operation(body) === 'Comments' ? { comments: connection([comment]) } : { issueRelations: connection([relation]) },\n errors: [{ message: 'Some fields were denied', extensions: { code: 'FORBIDDEN' } }] })\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n expect((await runIngestion(request(pipeline, resource), { ...env, retry: oneRetry, journal, destination, now: () => cutoff })).ok).toBe(false)\n expect(attempts).toBe(1)\n expect(destination.tables.size).toBe(0)\n expect((await journal.readCheckpoint(`linear.${resource}`)).lastSuccessSeq).toBe(0)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0)\n }\n})\n\ntest('malformed root and nested continuations fail before another request or successful checkpoint', async () => {\n for (const name of ['Comments', 'IssueRelations', 'IssueLabels', 'IssueHistoryParents', 'IssueHistory']) {\n for (const endCursor of [7, ' ', null]) {\n let attempts = 0\n const env = linearEnv((body) => {\n if (operation(body) !== name) return precedingResponse(body, name)\n attempts++\n return connectionFor(body, { nodes: [], pageInfo: { hasNextPage: true, endCursor } })\n })\n const pipeline = fixturePipeline()\n const resource = resourceFor(name), journal = createMemoryJournal()\n const result = await runIngestion(request(pipeline, resource), { ...env, journal, destination: createMemoryDestination(), now: () => cutoff })\n expect(result.ok, `${name}:${String(endCursor)}`).toBe(false)\n expect(attempts).toBe(1)\n expect((await journal.readCheckpoint(`linear.${resource}`)).envelope).toBeUndefined()\n expect((await journal.readCheckpoint(`linear.${resource}`)).lastSuccessSeq).toBe(0)\n }\n }\n})\n\ntest('cyclic root and nested pagination fails permanently without replaying a whole reader', async () => {\n for (const name of ['Comments', 'IssueRelations', 'IssueLabels', 'IssueHistoryParents', 'IssueHistory']) {\n const afters: unknown[] = []\n const env = linearEnv((body) => {\n if (operation(body) !== name) return precedingResponse(body, name)\n afters.push(body.variables.after)\n return connectionFor(body, connection([], body.variables.after === 'a' ? 'b' : 'a'))\n })\n const pipeline = fixturePipeline()\n const resource = resourceFor(name), journal = createMemoryJournal()\n const result = await runIngestion(request(pipeline, resource), { ...env, retry: oneRetry, journal, destination: createMemoryDestination(), now: () => cutoff })\n expect(result.ok, name).toBe(false)\n expect(afters).toEqual(name === 'IssueLabels' ? ['a', 'b'] : [null, 'a', 'b'])\n expect((await journal.readCheckpoint(`linear.${resource}`)).lastSuccessSeq).toBe(0)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0)\n }\n})\n\ntest('a repeated initial label cursor cannot publish the issue or retry its label read', async () => {\n const afters: unknown[] = []\n const env = linearEnv((body) => {\n if (operation(body) !== 'IssueLabels') return precedingResponse(body, 'IssueLabels')\n afters.push(body.variables.after)\n return connectionFor(body, connection([{ id: 'label-cyclic', name: 'Incomplete' }], 'a'))\n })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n const result = await runIngestion(request(pipeline, 'issues'), { ...env, retry: oneRetry, journal, destination, now: () => cutoff })\n\n expect(result.ok).toBe(false)\n expect(result.streams[0]?.error).toContain('repeated continuation')\n expect(afters).toEqual(['a'])\n expect(destination.tables.size).toBe(0)\n expect((await journal.readCheckpoint('linear.issues')).envelope).toBeUndefined()\n expect((await journal.readCheckpoint('linear.issues')).lastSuccessSeq).toBe(0)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0)\n})\n\ntest('malformed connections or provider identities cannot silently complete an empty-looking window', async () => {\n for (const payload of [\n { nodes: {}, pageInfo: { hasNextPage: false, endCursor: null } },\n { nodes: [], pageInfo: { hasNextPage: 'false', endCursor: null } },\n connection([{ ...comment, id: '' }]), connection([{ ...comment, updatedAt: 'invalid' }]),\n connection([{ ...comment, updatedAt: '2026-01-03T00:00:00Z' }]),\n ]) {\n let attempts = 0\n const env = linearEnv(() => { attempts++; return Response.json({ data: { comments: payload } }) })\n const pipeline = fixturePipeline()\n const journal = createMemoryJournal()\n expect((await runIngestion(request(pipeline, 'comments'), { ...env, journal, destination: createMemoryDestination(), now: () => cutoff })).ok).toBe(false)\n expect(attempts).toBe(1)\n expect((await journal.readCheckpoint('linear.comments')).envelope).toBeUndefined()\n }\n})\n\ntest('Linear rate limits honor exhausted reset headers across HTTP and GraphQL responses', async () => {\n for (const status of [200, 400, 429]) {\n for (const kind of ['requests', 'endpoint-requests', 'complexity']) {\n const reset = Date.now() + 60_000\n const run = await runUntilFirstRetry(() => Response.json({ errors: [{ extensions: { code: 'RATELIMITED' } }] }, {\n status, headers: { [`x-ratelimit-${kind}-remaining`]: '0', [`x-ratelimit-${kind}-reset`]: String(reset) },\n }))\n expect(run.requests).toBe(1)\n expect(run.retries.map((retry) => retry.errorClass)).toEqual(['rate_limited'])\n expect(run.retries[0]?.delay).toBeGreaterThanOrEqual(reset - Date.now())\n expect(run.retries[0]?.delay).toBeLessThanOrEqual(60_000)\n }\n }\n})\n\ntest('Linear HTTP429 chooses the latest exhausted reset and lets Retry-After take precedence', async () => {\n const reset = Date.now() + 60_000\n const headers = {\n 'x-ratelimit-requests-remaining': '0', 'x-ratelimit-requests-reset': String(reset - 30_000),\n 'x-ratelimit-endpoint-requests-remaining': '0', 'x-ratelimit-endpoint-requests-reset': String(reset),\n 'x-ratelimit-complexity-remaining': '1', 'x-ratelimit-complexity-reset': String(reset + 60_000),\n }\n const latest = await runUntilFirstRetry(() => new Response('Too many requests', { status: 429, headers }))\n expect(latest.retries.map((retry) => retry.errorClass)).toEqual(['rate_limited'])\n expect(latest.retries[0]?.delay).toBeGreaterThanOrEqual(reset - Date.now())\n expect(latest.retries[0]?.delay).toBeLessThanOrEqual(60_000)\n expect((await runUntilFirstRetry(() => new Response('', {\n status: 429, headers: { ...headers, 'Retry-After': '0' },\n }))).retries).toEqual([{ errorClass: 'rate_limited', delay: 0 }])\n for (const resetHeader of ['', 'garbage', '0', '-1']) {\n expect((await runUntilFirstRetry(() => new Response('', {\n status: 429, headers: { 'x-ratelimit-requests-remaining': '0', 'x-ratelimit-requests-reset': resetHeader },\n }))).retries).toEqual([{ errorClass: 'rate_limited', delay: undefined }])\n }\n expect(await runUntilFirstRetry(() => Response.json({ errors: [{ extensions: { code: 'FORBIDDEN' } }] }, {\n status: 400, headers,\n }))).toEqual({ outcome: 'failed', requests: 1, retries: [] })\n})\n\ntest('Linear HTTP429 reset delay is applied by the executor to exactly one page retry', async () => {\n let requests = 0, reset = 0, retriedAt = 0\n const server = Bun.serve({ port: 0, fetch: () => {\n requests++\n if (requests === 1) {\n reset = Date.now() + 100\n return new Response('Too many requests', { status: 429, headers: {\n 'x-ratelimit-requests-remaining': '0', 'x-ratelimit-requests-reset': String(reset),\n } })\n }\n retriedAt = Date.now()\n return response('comments', [comment])\n } })\n try {\n const env = { fetch: (_input: string | URL, init?: RequestInit) => fetch(`http://127.0.0.1:${server.port}/graphql`, init) }\n const journal = createMemoryJournal(), destination = createMemoryDestination()\n expect((await runIngestion(request(fixturePipeline(), 'comments'), { ...env, retry: oneRetry, journal, destination, now: () => cutoff })).ok).toBe(true)\n expect(requests).toBe(2)\n expect(retriedAt).toBeGreaterThanOrEqual(reset - 5)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled' && event.errorClass === 'rate_limited')).toHaveLength(1)\n expect(destination.tables.get('default.linear_comments_raw')).toHaveLength(1)\n expect((await journal.readCheckpoint('linear.comments')).envelope?.state).toEqual({ watermark: cutoff.toISOString() })\n } finally {\n await server.stop(true)\n }\n})\n\ntest('Linear checks its configuration when a stream runs, not when the module loads or a stream is selected', async () => {\n let requests = 0\n const pipeline = createLinearPipeline({ ...fixtureConfig, overlapMs: 1.5 })\n const selected = selectStreams([pipeline], [])\n expect(selected).toHaveLength(9)\n const env = linearEnv(() => { requests += 1; return Response.json({}) })\n const result = await runIngestion({ selected, backfill: undefined }, { ...env, journal: createMemoryJournal(), destination: createMemoryDestination(), now: () => cutoff })\n expect(result.streams.every((stream) => stream.outcome === 'failed' && /at overlapMs/.test(stream.error ?? ''))).toBe(true)\n expect(requests).toBe(0)\n})\n\ntest('Linear fails every stream before any request when the API key is missing', async () => {\n let requests = 0\n const pipeline = createLinearPipeline({ ...fixtureConfig, apiKey: undefined })\n const env = linearEnv(() => { requests += 1; return Response.json({}) })\n const result = await runIngestion(request(pipeline), { ...env, journal: createMemoryJournal(), destination: createMemoryDestination(), now: () => cutoff })\n expect(result.streams).toHaveLength(9)\n expect(result.streams.every((stream) => stream.outcome === 'failed' && stream.error?.includes('Set LINEAR_API_KEY or pass apiKey.'))).toBe(true)\n expect(requests).toBe(0)\n})\n\ntest('Linear fails a malformed provider payload at once and retries only a transient response', async () => {\n const retry = { retries: 2, minTimeout: 0, maxTimeout: 0 }\n let calls = 0\n const malformed = linearEnv(() => {\n calls += 1\n return Response.json({ data: { comments: { nodes: 'not-a-list', pageInfo: { hasNextPage: false, endCursor: null } } } })\n })\n const journal = createMemoryJournal()\n const result = await runIngestion(request(fixturePipeline(), 'comments'), { ...malformed, retry, journal, destination: createMemoryDestination(), now: () => cutoff })\n expect(result.streams[0]?.outcome).toBe('failed')\n expect(result.streams[0]?.error).toContain('Invalid input: expected array, received string')\n expect(calls).toBe(1)\n expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0)\n\n let unavailable = true\n const flaky = linearEnv((body) => {\n if (unavailable) { unavailable = false; return new Response('busy', { status: 503 }) }\n return fixtureResponse(body)\n })\n const recovered = createMemoryJournal()\n expect((await runIngestion(request(fixturePipeline(), 'comments'), { ...flaky, retry, journal: recovered, destination: createMemoryDestination(), now: () => cutoff })).ok).toBe(true)\n expect(recovered.events.filter((event) => event.eventKind === 'retry_scheduled').map((event) => event.errorClass)).toEqual(['transient'])\n})\n\nfunction fixturePipeline(config: LinearConfig = fixtureConfig): Pipeline {\n return createLinearPipeline(config)\n}\n\nfunction linearEnv(respond: Responder = fixtureResponse) {\n return { fetch: async (_input: string | URL, init?: RequestInit) => respond(JSON.parse(String(init?.body))), retry: { retries: 0 } }\n}\n\nfunction request(pipeline: Pipeline, resource?: string) {\n return { selected: selectStreams([pipeline], resource ? [`resource:${resource}`] : []).map((entry) => ({\n ...entry, stream: { ...entry.stream, batchSize: 1 },\n })), backfill: undefined }\n}\n\nasync function runUntilFirstRetry(respond: Responder) {\n let requests = 0\n const journal = createMemoryJournal(), cancel = new AbortController()\n const result = await runIngestion(request(fixturePipeline(), 'comments'), {\n ...linearEnv((body) => { requests++; return respond(body) }), retry: { retries: 1 }, signal: cancel.signal,\n journal: { ...journal, append: async (events) => {\n await journal.append(events)\n if (events.some((event) => event.eventKind === 'retry_scheduled')) setTimeout(() => cancel.abort())\n } },\n destination: createMemoryDestination(), now: () => cutoff,\n })\n const retries = journal.events.filter((event) => event.eventKind === 'retry_scheduled').map((event) => ({\n errorClass: event.errorClass, delay: event.retryAt && event.retryAt.getTime() - cutoff.getTime(),\n }))\n return { outcome: result.streams[0]?.outcome, requests, retries }\n}\n\nfunction operation(body: GraphqlRequest): string {\n const name = /query\\s+(\\w+)/.exec(body.query)?.[1]\n if (!name) throw new Error('Fixture received an unnamed GraphQL operation.')\n return name\n}\n\nfunction fixtureResponse(body: GraphqlRequest): Response {\n switch (operation(body)) {\n case 'Issues': return response('issues', [issue])\n case 'Comments': return response('comments', [comment])\n case 'Projects': return response('projects', [project])\n case 'ProjectUpdates': return response('projectUpdates', [projectUpdate])\n case 'Cycles': return response('cycles', [cycle])\n case 'Users': return response('users', [user])\n case 'Teams': return response('teams', [team])\n case 'IssueRelations': return response('issueRelations', [relation])\n case 'IssueHistoryParents': return response('issues', [{ id: issue.id, updatedAt: '2020-01-01T00:00:00Z' }])\n case 'IssueHistory': return Response.json({ data: { issue: { history: connection([history]) } } })\n default: throw new Error(`Unexpected Linear fixture operation: ${operation(body)}`)\n }\n}\n\nfunction connection(items: readonly unknown[], next: string | null = null) {\n return { nodes: items, pageInfo: { hasNextPage: next !== null, endCursor: next } }\n}\n\nfunction response(root: string, items: readonly unknown[], next: string | null = null): Response {\n return Response.json({ data: { [root]: connection(items, next) } })\n}\n\nfunction emptyResponse(body: GraphqlRequest): Response {\n return connectionFor(body, connection([]))\n}\n\nfunction connectionFor(body: GraphqlRequest, page: unknown): Response {\n const roots: Record = { Issues: 'issues', Comments: 'comments', Projects: 'projects', ProjectUpdates: 'projectUpdates',\n Cycles: 'cycles', Users: 'users', Teams: 'teams', IssueRelations: 'issueRelations', IssueHistoryParents: 'issues' }\n const root = roots[operation(body)]\n if (root) return Response.json({ data: { [root]: page } })\n if (operation(body) === 'IssueLabels') return Response.json({ data: { issue: { labels: page } } })\n if (operation(body) === 'IssueHistory') return Response.json({ data: { issue: { history: page } } })\n throw new Error(`Unexpected Linear fixture operation: ${operation(body)}`)\n}\n\nfunction resourceFor(name: string): string {\n return name === 'Comments' ? 'comments' : name === 'IssueRelations' ? 'issue_relations' : name === 'IssueLabels' ? 'issues' : 'issue_history'\n}\n\nfunction precedingResponse(body: GraphqlRequest, target: string): Response {\n if (target === 'IssueLabels') return response('issues', [{ ...issue, labels: connection([], 'a') }])\n return fixtureResponse(body)\n}\n" } ], "meta": { "chkit": { "formatVersion": 1, "version": "0.3.0", "changelog": [ { "version": "0.3.0", "changes": [ "Read configuration and the API key when a stream runs, so `generate`, `migrate`, and `chkit check` never depend on them; invalid settings or a missing key fail that run before any request. Requires zod 4 and chkit 0.2.0-beta.12.", "Send requests through the ingestion runtime, which retries only network failures, timeouts, retryable HTTP statuses, and GraphQL `RATELIMITED` errors (as HTTP 429); malformed payloads and other GraphQL errors fail at once.", "Set `apiKey` in the configuration to use another key, for example for a second workspace; it defaults to `LINEAR_API_KEY`." ] }, { "version": "0.2.1", "changes": [ "Honor exhausted request, endpoint, and complexity reset headers on HTTP 429 responses while preserving Retry-After precedence.", "Clarify that native ClickHouse JSON can omit explicit null properties and empty objects rather than retaining an exact JSON archive." ] }, { "version": "0.2.0", "changes": [ "Sync issues, comments, projects, project updates, cycles, users, and teams through independent overlapping updated-time windows, including archived and disabled resources.", "Add independent full-sync streams for issue relations and issue history; discover and paginate history for all accessible issues without relying on parent stream progress or modification times.", "Store each resource in its own raw table with provider IDs and relationship references; retain complete issue labels as strings and leave joins and metrics to ClickHouse.", "Use shared pagination, validated GraphQL responses, request-level retries and sink-acknowledged completion checkpoints; separate configuration, injectable requests, readers, and pipeline wiring.", "Existing issue IDs remain stable; migrate retained nested comment observations deliberately and populate the eight new destinations through their own initial syncs.", "Consume full pagination pages and use shared continuation-cycle detection while preserving independent resource checkpoints and GraphQL response validation." ] }, { "version": "0.1.0", "changes": [ "Introduce raw GraphQL issue ingestion." ] } ], "language": "typescript", "license": "MIT", "documentation": "https://chkit.obsessiondb.com/integrations/linear/", "logo": "https://chkit.obsessiondb.com/logos/linear.svg", "authentication": { "method": "Personal API key", "env": [ "LINEAR_API_KEY" ], "setup": [ "Provide LINEAR_API_KEY with read access to the selected resources.", "Keep the API key in the runtime environment and rotate it according to the provider policy." ], "documentation": "https://linear.app/developers/graphql" }, "chkit": "^0.2.0-beta.12", "ingest": "^0.2.0-beta.12", "clickhouse": ">=25.3.0", "root": "src/integrations/linear", "entry": "index.ts", "exports": [ "linearPipeline", "createLinearPipeline", "linear_issuesRaw", "linear_commentsRaw", "linear_projectsRaw", "linear_projectUpdatesRaw", "linear_cyclesRaw", "linear_usersRaw", "linear_teamsRaw", "linear_issueRelationsRaw", "linear_issueHistoryRaw" ], "resources": [ { "name": "issues", "title": "Issues", "table": "linear_issues_raw", "description": "Archived and active issue fields, relationship IDs, and fully paginated label names as strings.", "scopes": [], "strategy": "timestamp", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] }, { "name": "comments", "title": "Comments", "table": "linear_comments_raw", "description": "Raw comments selected by their own update times, with nullable issue and other parent references.", "scopes": [], "strategy": "timestamp", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] }, { "name": "projects", "title": "Projects", "table": "linear_projects_raw", "description": "Project metadata and provider relationship references selected by project update times.", "scopes": [], "strategy": "timestamp", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] }, { "name": "project_updates", "title": "Project updates", "table": "linear_project_updates_raw", "description": "Authored progress and health updates with project and author references.", "scopes": [], "strategy": "timestamp", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] }, { "name": "cycles", "title": "Cycles", "table": "linear_cycles_raw", "description": "Cycle dates, descriptions, and team references selected by cycle update times.", "scopes": [], "strategy": "timestamp", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] }, { "name": "users", "title": "Users", "table": "linear_users_raw", "description": "Accessible user metadata, including disabled users, selected by user update times.", "scopes": [], "strategy": "timestamp", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] }, { "name": "teams", "title": "Teams", "table": "linear_teams_raw", "description": "Accessible team metadata selected by team update times.", "scopes": [], "strategy": "timestamp", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] }, { "name": "issue_relations", "title": "Issue relations", "table": "linear_issue_relations_raw", "description": "Complete accessible relation records with type and both directed issue references; no reliable root change filter exists.", "scopes": [], "strategy": "full", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] }, { "name": "issue_history", "title": "Issue history", "table": "linear_issue_history_raw", "description": "Complete accessible history for independently discovered issues; the parent history connection has no timestamp filter.", "scopes": [], "strategy": "full", "endpoints": [ { "method": "POST", "path": "/graphql", "documentation": "https://linear.app/developers/graphql" } ] } ], "views": [], "sync": { "description": "One workspace pipeline groups nine independent raw streams. Seven resources use bounded updatedAt windows with five-minute overlap; issue relations and history use fullSync. Each stream completes only after destination acknowledgement.", "schedule": "Run bunx chkit ingest run --tag provider:linear from a scheduler.", "deletions": "Deleted records and removed relations remain stored; absence is not a tombstone. Comments have their own update windows. Periodic reconciliation refreshes older observations and label renames beyond the issue overlap; retained legacy nested comments require deliberate migration." }, "env": { "LINEAR_API_KEY": "" }, "fileHashes": { "src/integrations/linear/README.md": "6f0e77d1728ec087f7d244845bc11cc28174516a094cb3f50f9258d59f68523a", "src/integrations/linear/index.ts": "819a578cd47a80021d7a27fbc27ce25e3b648d45119822d2fedd81f9fa63d83b", "src/integrations/linear/config.ts": "77374e701ffdebfffc9b83356348ee47611ac25d1d6b5ac3394a6b3ad17d480a", "src/integrations/linear/client.ts": "7205d1f6ab4a1f0f4af1309d4d518cdc453c4607bfe87abe17b0bef94d617cac", "src/integrations/linear/pipeline.ts": "b5eef38170186babd1b9432e0abe8fc4ef6d4bf864c7dd8b517d5885ae0f65ed", "src/integrations/linear/sources/issues.ts": "925d200fa9624541b8dad3150c5ded94a126edbdfb62858c019b4bfbb0d9b4e8", "src/integrations/linear/sources/common.ts": "fbc9272bc241830ac4963edeebd199cf971ac84145a9a33942781a7764e24805", "src/integrations/linear/sources/comments.ts": "9573b96d5ea7ec6846a9c8425706dad8c940031a427f0f126c4b3c7ddae6eb25", "src/integrations/linear/sources/projects.ts": "9332c4ccd3dede3efc22cd769a8b7677f39db2795ad5e76eec1bfba0fa5c512a", "src/integrations/linear/sources/project-updates.ts": "cf8823fb8e5b3a5906892f6880c8b85f86fddefff0f9e9c7a15b8b0f343b1dd7", "src/integrations/linear/sources/cycles.ts": "d9161eb4ec7df6e22b49ef584015e136c3be321870ed403b55e02e3216f21b78", "src/integrations/linear/sources/users.ts": "66bf3418949a98e2cd9240dfc5c70ce9b4615231ab3a8bf326b31123fc1fa596", "src/integrations/linear/sources/teams.ts": "acd343844a127f3b0cc91aa46e632bd0cbf9be22bc2ebb2b03bf51ef3d2c4dc4", "src/integrations/linear/sources/issue-relations.ts": "8ef5a791b2d5ee740d508dc1205502d2bdbd580516c082c7b1141392884c2a14", "src/integrations/linear/sources/issue-history.ts": "a0f1d8df5c091f1636c462ff45d1ef6349b4a028d7ba95e0d881e6837ff0372e", "src/integrations/linear/tests/basic.test.ts": "1abb689967c51649193bc3c5e4b43b01b035f41746217c616838cf732b7a8a36" } } } }