⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat(import): import from Linear (#495)
Thomas Gallawayf3c5dc635820
diff --git a/apps/api/src/modules/import-export/__tests__/integration/import-export.test.ts b/apps/api/src/modules/import-export/__tests__/integration/import-export.test.tsindex f39a7ee1..69094b90 100644--- a/apps/api/src/modules/import-export/__tests__/integration/import-export.test.ts+++ b/apps/api/src/modules/import-export/__tests__/integration/import-export.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, beforeEach } from 'bun:test';import { db, importJob } from '@repo/db';import { eq } from 'drizzle-orm';+import { decryptSecret } from '@repo/crypto';import { authedApi } from '#tests/helpers/app';import { signUpTestUser } from '#tests/helpers/auth';import { resetDb } from '#tests/helpers/db';@@ -325,6 +326,119 @@ describe('import jobs', () => {});});+ describe('linear', () => {+ const linearBody = {+ source: 'linear' as const,+ apiToken: 'lin_api_test_key',+ teamId: 'team-ato',+ teamKey: 'ATO',+ projectFilter: 'project' as const,+ projectId: 'proj-tool',+ };++ it('creates a pending Linear job and stores the credential and config the worker reads', async () => {+ const { api } = await setupOwnerProject();++ const res = await jobs(api).post({+ ...linearBody,+ stateOverrides: { 'state-triage': 'unstarted' },+ });++ expect(res.status).toBe(201);+ expect(res.data).toMatchObject({+ source: 'linear',+ phase: 'discover',+ status: 'pending',+ counts: zeroedCounts,+ });+ expect(res.data).not.toHaveProperty('apiToken');+ const [row] = await db.select().from(importJob).where(eq(importJob.id, res.data!.id));+ expect(row!.config).toEqual({+ teamId: 'team-ato',+ teamKey: 'ATO',+ projectFilter: 'project',+ projectId: 'proj-tool',+ unmatchedUserPolicy: 'unassigned',+ stateOverrides: { 'state-triage': 'unstarted' },+ });+ const credential = decryptSecret({+ ciphertext: row!.credentialCiphertext!,+ iv: row!.credentialIv!,+ authTag: row!.credentialAuthTag!,+ });+ expect(JSON.parse(credential)).toEqual({ apiKey: 'lin_api_test_key' });+ });++ it("creates a job for the team's issues with no project, listed next to Plane jobs", async () => {+ const { api } = await setupOwnerProject();+ const plane = (await jobs(api).post(validBody)).data!;++ const { projectId: _projectId, ...team } = linearBody;+ const res = await jobs(api).post({ ...team, projectFilter: 'none' as const });++ expect(res.status).toBe(201);+ const [row] = await db.select().from(importJob).where(eq(importJob.id, res.data!.id));+ expect(row!.config).toMatchObject({ projectFilter: 'none', projectId: null });+ const list = await jobs(api).get();+ expect(list.data?.map((j) => [j.id, j.source])).toEqual([+ [res.data!.id, 'linear'],+ [plane.id, 'plane'],+ ]);+ });++ it.each([+ ['a missing teamKey', { teamKey: undefined }],+ ['an empty apiToken', { apiToken: '' }],+ ['a blank apiToken', { apiToken: ' ' }],+ ['an unknown projectFilter', { projectFilter: 'some' }],+ ['a project import with no projectId', { projectId: undefined }],+ ['a no-project import with a projectId', { projectFilter: 'none' }],+ ])('rejects %s', async (_case, change) => {+ const { api } = await setupOwnerProject();+ const res = await jobs(api).post({ ...linearBody, ...change } as never);+ expect(res.status).toBe(400);+ });++ it('rejects a Plane body sent as a Linear job', async () => {+ const { api } = await setupOwnerProject();+ const res = await jobs(api).post({ ...validBody, source: 'linear' } as never);+ expect(res.status).toBe(400);+ });++ it('rejects a missing or blank field on the Linear endpoints before calling Linear', async () => {+ const { api } = await setupOwnerProject();+ expect((await jobs(api)['linear-test-connection'].post({} as never)).status).toBe(400);+ expect((await jobs(api)['linear-test-connection'].post({ apiToken: ' ' })).status).toBe(+ 400,+ );+ expect(+ (await jobs(api)['linear-preview'].post({ apiToken: 'lin_api_test_key' } as never)).status,+ ).toBe(400);+ expect(+ (await jobs(api)['linear-preview'].post({ apiToken: 'lin_api_test_key', teamId: ' ' }))+ .status,+ ).toBe(400);+ });++ it('denies a member whose role lacks the import_export permission', async () => {+ const { api } = await setupOwnerProject();+ const member = await addMember(api);+ expect(+ (await jobs(member)['linear-test-connection'].post({ apiToken: 'lin_api_test_key' }))+ .status,+ ).toBe(403);+ expect(+ (+ await jobs(member)['linear-preview'].post({+ apiToken: 'lin_api_test_key',+ teamId: 'team-ato',+ })+ ).status,+ ).toBe(403);+ expect((await jobs(member).post(linearBody)).status).toBe(403);+ });+ });+describe('access', () => {it('returns 404 for an unknown project', async () => {const { api } = await setupOwnerProject();diff --git a/apps/api/src/modules/import-export/__tests__/unit/linear.test.ts b/apps/api/src/modules/import-export/__tests__/unit/linear.test.tsnew file mode 100644index 00000000..56b96740--- /dev/null+++ b/apps/api/src/modules/import-export/__tests__/unit/linear.test.ts@@ -0,0 +1,257 @@+import { describe, it, expect } from 'bun:test';+import type { PinnedRequestInit } from '@repo/net';+import { HttpError } from '#shared/lib';+import {+ LINEAR_GRAPHQL_URL,+ linearJobFields,+ previewLinearStates,+ testLinearConnection,+ type LinearFetch,+} from '../../linear';++interface SentRequest {+ url: string;+ init: PinnedRequestInit | undefined;+}++function answering(responses: (Response | Error)[], sent: SentRequest[] = []): LinearFetch {+ const queue = [...responses];+ return async (url, init) => {+ sent.push({ url, init });+ const next = queue.shift();+ if (!next) throw new Error(`unexpected request ${url}`);+ if (next instanceof Error) throw next;+ return next;+ };+}++function page<T>(nodes: T[], endCursor: string | null, hasNextPage: boolean) {+ return { connection: { nodes, pageInfo: { hasNextPage, endCursor } } };+}++async function httpError(promise: Promise<unknown>): Promise<HttpError> {+ const error = await promise.catch((e: unknown) => e);+ expect(error).toBeInstanceOf(HttpError);+ return error as HttpError;+}++describe('testLinearConnection', () => {+ it('sends the bare key to Linear only and lists every team with its projects', async () => {+ const sent: SentRequest[] = [];+ const fetch = answering(+ [+ Response.json({+ data: page(+ [+ { id: 't1', key: 'ATO', name: 'Atomlab' },+ { id: 't2', key: 'AMA', name: 'AmandaHuie' },+ ],+ null,+ false,+ ),+ }),+ Response.json({+ data: page(+ [{ id: 'p2', name: 'The Tool', teams: { nodes: [{ id: 't1' }] } }],+ 'c1',+ true,+ ),+ }),+ Response.json({+ data: page(+ [{ id: 'p1', name: 'HeadInMyVoices', teams: { nodes: [{ id: 't1' }, { id: 't2' }] } }],+ null,+ false,+ ),+ }),+ ],+ sent,+ );++ expect(await testLinearConnection(' lin_api_key ', fetch)).toEqual({+ teams: [+ {+ id: 't1',+ key: 'ATO',+ name: 'Atomlab',+ projects: [+ { id: 'p1', name: 'HeadInMyVoices' },+ { id: 'p2', name: 'The Tool' },+ ],+ },+ {+ id: 't2',+ key: 'AMA',+ name: 'AmandaHuie',+ projects: [{ id: 'p1', name: 'HeadInMyVoices' }],+ },+ ],+ });+ expect(sent.map((r) => r.url)).toEqual([+ LINEAR_GRAPHQL_URL,+ LINEAR_GRAPHQL_URL,+ LINEAR_GRAPHQL_URL,+ ]);+ expect(sent[0]!.init).toMatchObject({+ method: 'POST',+ headers: { Authorization: 'lin_api_key', 'Content-Type': 'application/json' },+ });+ expect(JSON.parse(String(sent[2]!.init?.body)).variables).toEqual({ after: 'c1' });+ });++ it('answers 400 when Linear rejects the key', async () => {+ const fetch = answering([+ Response.json(+ {+ errors: [+ {+ message: 'Authentication required, not authenticated',+ extensions: { code: 'AUTHENTICATION_ERROR' },+ },+ ],+ },+ { status: 401 },+ ),+ ]);+ const error = await httpError(testLinearConnection('lin_api_bad', fetch));+ expect(error.status).toBe(400);+ expect(error.message).toBe('Linear rejected the API key.');+ });++ it('answers 502 on a rate limit, an unreachable Linear, or a failed request', async () => {+ const limited = answering([+ Response.json(+ { errors: [{ message: 'Rate limit exceeded', extensions: { code: 'RATELIMITED' } }] },+ { status: 400 },+ ),+ ]);+ expect((await httpError(testLinearConnection('k', limited))).message).toBe(+ "Linear's rate limit was reached. Try again in a few minutes.",+ );+ const down = answering([new Error('connect ECONNREFUSED')]);+ expect((await httpError(testLinearConnection('k', down))).message).toBe(+ 'Linear could not be reached.',+ );+ const broken = answering([new Response('oops', { status: 500 })]);+ const error = await httpError(testLinearConnection('k', broken));+ expect([error.status, error.message]).toEqual([502, 'Linear request failed with status 500.']);+ });++ it('refuses a blank key without calling Linear', async () => {+ const sent: SentRequest[] = [];+ const error = await httpError(testLinearConnection(' ', answering([], sent)));+ expect([error.status, error.message]).toEqual([400, 'apiToken is required']);+ expect(sent).toEqual([]);+ });+});++describe('previewLinearStates', () => {+ it("lists the team's states in Linear's order with the category each maps to", async () => {+ const sent: SentRequest[] = [];+ const fetch = answering(+ [+ Response.json({+ data: {+ team: page(+ [+ { id: 's3', name: 'Done', type: 'completed', position: 3 },+ { id: 's1', name: 'Triage', type: 'triage', position: 0 },+ { id: 's4', name: 'Duplicate', type: 'duplicate', position: 5 },+ { id: 's2', name: 'In Review', type: 'started', position: 2 },+ ],+ null,+ false,+ ),+ },+ }),+ ],+ sent,+ );++ expect(await previewLinearStates('k', 'team-1', fetch)).toEqual({+ states: [+ { id: 's1', name: 'Triage', category: 'backlog' },+ { id: 's2', name: 'In Review', category: 'started' },+ { id: 's3', name: 'Done', category: 'completed' },+ { id: 's4', name: 'Duplicate', category: 'canceled' },+ ],+ });+ expect(JSON.parse(String(sent[0]!.init?.body)).variables).toEqual({+ teamId: 'team-1',+ after: null,+ });+ });+});++describe('Linear user errors', () => {+ it('answers 400 when the team does not exist or the key cannot see it', async () => {+ const fetch = answering([Response.json({ data: { team: null } })]);+ const error = await httpError(previewLinearStates('k', 'team-gone', fetch));+ expect([error.status, error.message]).toEqual([400, 'Linear team not found.']);+ });++ it.each([+ ['INVALID_INPUT', 'invalid input', 'Entity not found: Team', 'Could not find referenced Team.'],+ ['FORBIDDEN', 'forbidden', 'Forbidden', 'You do not have access to this team.'],+ ])('answers 400 with what Linear said for a %s error', async (code, type, message, shown) => {+ const fetch = answering([+ Response.json({+ data: null,+ errors: [+ {+ message,+ extensions: { code, type, userError: true, userPresentableMessage: shown },+ },+ ],+ }),+ ]);+ const error = await httpError(previewLinearStates('k', 'team-1', fetch));+ expect([error.status, error.message]).toEqual([400, `Linear refused the request: ${shown}`]);+ });++ it("still answers 502 for an error that is not the caller's", async () => {+ const fetch = answering([+ Response.json({+ data: null,+ errors: [{ message: 'boom', extensions: { code: 'INTERNAL_ERROR', userError: false } }],+ }),+ ]);+ const error = await httpError(previewLinearStates('k', 'team-1', fetch));+ expect([error.status, error.message]).toEqual([502, 'Linear request failed with status 200.']);+ });+});++describe('linearJobFields', () => {+ const base = {+ source: 'linear' as const,+ apiToken: ' lin_api_key ',+ teamId: 'team-1',+ teamKey: 'ATO',+ };++ it('stores the key as the credential and the scope as the config the worker reads', () => {+ expect(linearJobFields({ ...base, projectFilter: 'project', projectId: 'p-1' })).toEqual({+ source: 'linear',+ credential: { apiKey: 'lin_api_key' },+ config: { teamId: 'team-1', teamKey: 'ATO', projectFilter: 'project', projectId: 'p-1' },+ });+ expect(linearJobFields({ ...base, projectFilter: 'none' }).config).toEqual({+ teamId: 'team-1',+ teamKey: 'ATO',+ projectFilter: 'none',+ projectId: null,+ });+ });++ it('refuses a scope that does not match its filter', () => {+ expect(() => linearJobFields({ ...base, projectFilter: 'project' })).toThrow(+ 'projectId is required to import a project',+ );+ expect(() => linearJobFields({ ...base, projectFilter: 'none', projectId: 'p-1' })).toThrow(+ 'projectId must be empty to import issues with no project',+ );+ expect(() => linearJobFields({ ...base, teamKey: ' ', projectFilter: 'none' })).toThrow(+ 'teamKey is required',+ );+ });+});diff --git a/apps/api/src/modules/import-export/index.ts b/apps/api/src/modules/import-export/index.tsindex 292ea853..a0cdc799 100644--- a/apps/api/src/modules/import-export/index.ts+++ b/apps/api/src/modules/import-export/index.ts@@ -8,11 +8,15 @@ import {ImportJobResponse,TestConnectionResponse,PlanePreviewResponse,+ LinearTestConnectionResponse,+ LinearPreviewResponse,ProjectExportResponse,createImportJobBody,importJobParams,testConnectionBody,planePreviewBody,+ linearConnectionBody,+ linearPreviewBody,} from './model';import {cancelImportJob,@@ -26,6 +30,7 @@ import {testPlaneStatesPreview,} from './service';import { exportProject } from './export';+import { previewLinearStates, testLinearConnection } from './linear';// Import jobs bring issues from an external tracker into a project. Creating one// stores an encrypted credential and leaves it 'pending' for the worker@@ -78,6 +83,38 @@ export const importExportRoutes = new Elysia({},)+ .post(+ '/projects/:projectKey/import-jobs/linear-test-connection',+ ({ body }) => testLinearConnection(body.apiToken),+ {+ permission: ['import_export', 'create'],+ body: linearConnectionBody,+ response: { 200: LinearTestConnectionResponse, ...commonErrors, ...errors(502) },+ detail: {+ summary: 'Test a Linear API key',+ description:+ 'Validate a Linear personal API key live, without storing anything. Returns the ' ++ 'teams it can see, each with its projects, to pick what to import from.',+ },+ },+ )++ .post(+ '/projects/:projectKey/import-jobs/linear-preview',+ ({ body }) => previewLinearStates(body.apiToken, body.teamId),+ {+ permission: ['import_export', 'create'],+ body: linearPreviewBody,+ response: { 200: LinearPreviewResponse, ...commonErrors, ...errors(502) },+ detail: {+ summary: 'Preview a Linear team before importing from it',+ description:+ "Fetch the team's workflow states, each with the category itsaplan would " ++ 'automatically map it to, for review before a job is created.',+ },+ },+ )+.get('/projects/:projectKey/import-jobs/export', ({ project }) => exportProject(project.id), {permission: ['import_export', 'create'],response: { 200: ProjectExportResponse, ...accessErrors },@@ -101,9 +138,10 @@ export const importExportRoutes = new Elysia({body: createImportJobBody,response: { 201: ImportJobResponse, ...commonErrors },detail: {- summary: 'Create a Plane import job',+ summary: 'Create an import job',description:- "Encrypt and store the submitted credential and leave the job 'pending' for the worker.",+ "Create a Plane job, or a Linear one with source 'linear'. Encrypt and store the " ++ "submitted credential and leave the job 'pending' for the worker.",},},)diff --git a/apps/api/src/modules/import-export/linear.ts b/apps/api/src/modules/import-export/linear.tsnew file mode 100644index 00000000..920103f7--- /dev/null+++ b/apps/api/src/modules/import-export/linear.ts@@ -0,0 +1,251 @@+import { HttpError } from '#shared/lib';+import { pinnedFetch } from '#shared/net';++// The Linear side of import jobs: checking a personal API key, listing the teams+// and projects it can see, previewing a team's workflow states, and validating a+// job's Linear fields. Linear's endpoint is fixed, so no user-supplied URL is ever+// fetched; the key is sent as "Authorization: <key>" (no "Bearer"). The worker's+// own reader is apps/worker/src/linear-adapter.ts; the api does not depend on the+// worker, so the small state mapping below is repeated here, as Plane's is.++export const LINEAR_GRAPHQL_URL = 'https://api.linear.app/graphql';+const PAGE_SIZE = 50;++type StateCategory = 'backlog' | 'unstarted' | 'started' | 'completed' | 'canceled';+export type LinearFetch = typeof pinnedFetch;++export interface LinearProjectOption {+ id: string;+ name: string;+}++export interface LinearTeamOption {+ id: string;+ key: string;+ name: string;+ projects: LinearProjectOption[];+}++export interface LinearStateOption {+ id: string;+ name: string;+ category: StateCategory;+}++export interface CreateLinearImportJobInput {+ source: 'linear';+ apiToken: string;+ teamId: string;+ teamKey: string;+ projectFilter: 'project' | 'none';+ projectId?: string;+}++interface Connection<T> {+ nodes: T[];+ pageInfo: { hasNextPage: boolean; endCursor: string | null };+}++interface GraphqlError {+ message: string;+ extensions?: { code?: string; userError?: boolean; userPresentableMessage?: string };+}++interface GraphqlResponse<D> {+ data?: D | null;+ errors?: GraphqlError[];+}++const TEAMS_QUERY = `query Teams($after: String) {+ connection: teams(first: ${PAGE_SIZE}, after: $after) {+ nodes { id key name }+ pageInfo { hasNextPage endCursor }+ }+}`;++const PROJECTS_QUERY = `query Projects($after: String) {+ connection: projects(first: ${PAGE_SIZE}, after: $after, includeArchived: true) {+ nodes { id name teams(first: ${PAGE_SIZE}) { nodes { id } } }+ pageInfo { hasNextPage endCursor }+ }+}`;++const STATES_QUERY = `query States($teamId: String!, $after: String) {+ team(id: $teamId) {+ connection: states(first: ${PAGE_SIZE}, after: $after, includeArchived: true) {+ nodes { id name type position }+ pageInfo { hasNextPage endCursor }+ }+ }+}`;++const USER_ERROR_CODES = new Set(['INVALID_INPUT', 'FORBIDDEN']);++const STATE_CATEGORY_MAP: Record<string, StateCategory> = {+ triage: 'backlog',+ backlog: 'backlog',+ unstarted: 'unstarted',+ started: 'started',+ completed: 'completed',+ canceled: 'canceled',+ duplicate: 'canceled',+};++async function linearQuery<D>(+ apiKey: string,+ query: string,+ variables: Record<string, unknown>,+ fetch: LinearFetch,+): Promise<D> {+ let response: Response;+ try {+ response = await fetch(LINEAR_GRAPHQL_URL, {+ method: 'POST',+ headers: { Authorization: apiKey, 'Content-Type': 'application/json' },+ body: JSON.stringify({ query, variables }),+ timeoutMs: 15_000,+ });+ } catch (err) {+ if (err instanceof HttpError) throw err;+ throw new HttpError(502, 'Linear could not be reached.');+ }+ const body = (await response.json().catch(() => ({}))) as GraphqlResponse<D>;+ const codes = (body.errors ?? []).map((e) => e.extensions?.code);+ if (response.status === 401 || codes.includes('AUTHENTICATION_ERROR')) {+ throw new HttpError(400, 'Linear rejected the API key.');+ }+ if (response.status === 429 || codes.includes('RATELIMITED')) {+ throw new HttpError(502, "Linear's rate limit was reached. Try again in a few minutes.");+ }+ // A wrong team id, or one the key cannot see: the caller's mistake, not Linear's.+ const userError = (body.errors ?? []).find(+ (e) => e.extensions?.userError || USER_ERROR_CODES.has(e.extensions?.code ?? ''),+ );+ if (userError) {+ const shown = userError.extensions?.userPresentableMessage ?? userError.message;+ throw new HttpError(400, `Linear refused the request: ${shown}`);+ }+ if (!response.ok || !body.data || codes.length > 0) {+ throw new HttpError(502, `Linear request failed with status ${response.status}.`);+ }+ return body.data;+}++async function linearPaginate<T, D>(+ apiKey: string,+ query: string,+ variables: Record<string, unknown>,+ connectionOf: (data: D) => Connection<T>,+ fetch: LinearFetch,+): Promise<T[]> {+ const all: T[] = [];+ let after: string | null = null;+ do {+ const data: D = await linearQuery<D>(apiKey, query, { ...variables, after }, fetch);+ const connection = connectionOf(data);+ all.push(...connection.nodes);+ after = connection.pageInfo.hasNextPage ? connection.pageInfo.endCursor : null;+ } while (after !== null);+ return all;+}++function requireKey(apiToken: string): string {+ const apiKey = apiToken.trim();+ if (!apiKey) throw new HttpError(400, 'apiToken is required');+ return apiKey;+}++// Confirms the key works before anything is stored, and returns every team it can+// see with that team's projects (archived ones included: an archive import wants+// them). A project shared by two teams is listed under both.+export async function testLinearConnection(+ apiToken: string,+ fetch: LinearFetch = pinnedFetch,+): Promise<{ teams: LinearTeamOption[] }> {+ const apiKey = requireKey(apiToken);+ type TeamNode = { id: string; key: string; name: string };+ type ProjectNode = { id: string; name: string; teams: { nodes: { id: string }[] } };+ const teams = await linearPaginate<TeamNode, { connection: Connection<TeamNode> }>(+ apiKey,+ TEAMS_QUERY,+ {},+ (data) => data.connection,+ fetch,+ );+ const projects = await linearPaginate<ProjectNode, { connection: Connection<ProjectNode> }>(+ apiKey,+ PROJECTS_QUERY,+ {},+ (data) => data.connection,+ fetch,+ );+ return {+ teams: teams.map((team) => ({+ id: team.id,+ key: team.key,+ name: team.name,+ projects: projects+ .filter((p) => p.teams.nodes.some((t) => t.id === team.id))+ .map((p) => ({ id: p.id, name: p.name }))+ .sort((a, b) => a.name.localeCompare(b.name)),+ })),+ };+}++// A team's workflow states in Linear's own order, each with the category the+// import would map it to, for the mapping review step.+export async function previewLinearStates(+ apiToken: string,+ teamId: string,+ fetch: LinearFetch = pinnedFetch,+): Promise<{ states: LinearStateOption[] }> {+ const apiKey = requireKey(apiToken);+ const id = teamId.trim();+ if (!id) throw new HttpError(400, 'teamId is required');+ type StateNode = { id: string; name: string; type: string; position: number };+ const states = await linearPaginate<+ StateNode,+ { team: { connection: Connection<StateNode> } | null }+ >(+ apiKey,+ STATES_QUERY,+ { teamId: id },+ (data) => {+ if (!data.team) throw new HttpError(400, 'Linear team not found.');+ return data.team.connection;+ },+ fetch,+ );+ return {+ states: [...states]+ .sort((a, b) => a.position - b.position)+ .map((s) => ({ id: s.id, name: s.name, category: STATE_CATEGORY_MAP[s.type] ?? 'backlog' })),+ };+}++// What createImportJob stores for a Linear job: the credential and config the+// worker's import-sources.ts reads back.+export function linearJobFields(input: CreateLinearImportJobInput) {+ const apiKey = requireKey(input.apiToken);+ const teamId = input.teamId.trim();+ const teamKey = input.teamKey.trim();+ const projectId = input.projectId?.trim() ?? '';+ if (!teamId) throw new HttpError(400, 'teamId is required');+ if (!teamKey) throw new HttpError(400, 'teamKey is required');+ if (input.projectFilter === 'project' && !projectId) {+ throw new HttpError(400, 'projectId is required to import a project');+ }+ if (input.projectFilter === 'none' && projectId) {+ throw new HttpError(400, 'projectId must be empty to import issues with no project');+ }+ return {+ source: 'linear' as const,+ credential: { apiKey },+ config: {+ teamId,+ teamKey,+ projectFilter: input.projectFilter,+ projectId: input.projectFilter === 'project' ? projectId : null,+ },+ };+}diff --git a/apps/api/src/modules/import-export/model.ts b/apps/api/src/modules/import-export/model.tsindex 9e7812e3..eeeed034 100644--- a/apps/api/src/modules/import-export/model.ts+++ b/apps/api/src/modules/import-export/model.ts@@ -4,9 +4,25 @@ export const importJobParams = t.Object({ id: t.Numeric() });const stateCategory = t.UnionEnum(['backlog', 'unstarted', 'started', 'completed', 'canceled']);+const importJobChoices = {+ unmatchedUserPolicy: t.Optional(+ t.UnionEnum(['unassigned', 'skip'], {+ description:+ 'How to handle an assignee or comment author with no matching project member by email. ' ++ "'unassigned' (default) leaves the field empty; 'skip' drops the assignment or comment.",+ }),+ ),+ stateOverrides: t.Optional(+ t.Record(t.String(), stateCategory, {+ description: 'Source state id -> itsaplan state category, overriding the automatic mapping.',+ }),+ ),+};+// The fields Plane needs to reach the source project, plus the mapping choices made-// at creation time.-export const createImportJobBody = t.Object({+// at creation time. A body without `source` is a Plane job.+const planeImportJobBody = t.Object({+ source: t.Optional(t.Literal('plane')),baseUrl: t.String({ minLength: 1, description: 'Origin of the source Plane instance.' }),workspaceSlug: t.String({ minLength: 1 }),apiToken: t.String({ minLength: 1, description: 'Plane workspace or personal API key.' }),@@ -17,20 +33,39 @@ export const createImportJobBody = t.Object({'The Plane project\'s own short identifier (e.g. "ROOMS"), used to recognize and ' +'rewrite cross-references like "ROOMS-524" in imported text.',}),- unmatchedUserPolicy: t.Optional(- t.UnionEnum(['unassigned', 'skip'], {- description:- 'How to handle an assignee or comment author with no matching project member by email. ' +- "'unassigned' (default) leaves the field empty; 'skip' drops the assignment or comment.",- }),- ),- stateOverrides: t.Optional(- t.Record(t.String(), stateCategory, {- description: 'Plane state id -> itsaplan state category, overriding the automatic mapping.',+ ...importJobChoices,+});++// One Linear team, and one of its projects or its issues with no project.+const linearImportJobBody = t.Object({+ source: t.Literal('linear'),+ apiToken: t.String({+ minLength: 1,+ description: 'Linear personal API key; read-only is enough.',+ }),+ teamId: t.String({ minLength: 1, description: 'The Linear team id to import from.' }),+ teamKey: t.String({+ minLength: 1,+ description:+ 'The team\'s issue-key prefix (e.g. "ATO"), used to recognize and rewrite ' ++ 'cross-references like "ATO-505" in imported text.',+ }),+ projectFilter: t.UnionEnum(['project', 'none'], {+ description:+ "'project' imports one project of the team; 'none' imports the team's issues that " ++ 'belong to no project.',+ }),+ projectId: t.Optional(+ t.String({+ minLength: 1,+ description: "The Linear project id, when projectFilter is 'project'.",}),),+ ...importJobChoices,});+export const createImportJobBody = t.Union([planeImportJobBody, linearImportJobBody]);+export const testConnectionBody = t.Object({baseUrl: t.String({ minLength: 1 }),workspaceSlug: t.String({ minLength: 1 }),@@ -52,6 +87,28 @@ export const PlanePreviewResponse = t.Object({states: t.Array(t.Object({ id: t.String(), name: t.String(), category: stateCategory })),});+export const linearConnectionBody = t.Object({+ apiToken: t.String({ minLength: 1, description: 'Linear personal API key.' }),+});++export const LinearTestConnectionResponse = t.Object({+ teams: t.Array(+ t.Object({+ id: t.String(),+ key: t.String(),+ name: t.String(),+ projects: t.Array(t.Object({ id: t.String(), name: t.String() })),+ }),+ ),+});++export const linearPreviewBody = t.Object({+ apiToken: t.String({ minLength: 1 }),+ teamId: t.String({ minLength: 1 }),+});++export const LinearPreviewResponse = PlanePreviewResponse;+// Mirrors import_record_source_entity_type_check in packages/db/src/schema/app.ts.const entityCount = t.Object({ discovered: t.Number(), created: t.Number() });const CountsResponse = t.Object({@@ -103,7 +160,7 @@ export const ProjectExportResponse = t.Object({export const ImportJobResponse = t.Object({id: t.Number(),projectId: t.Number(),- source: t.Literal('plane'),+ source: t.UnionEnum(['plane', 'linear']),phase: t.UnionEnum(['discover', 'create', 'link', 'rewrite', 'attachments', 'done']),status: t.UnionEnum(['pending', 'running', 'paused', 'completed', 'failed']),counts: CountsResponse,diff --git a/apps/api/src/modules/import-export/service.ts b/apps/api/src/modules/import-export/service.tsindex eef176ac..15b42a19 100644--- a/apps/api/src/modules/import-export/service.ts+++ b/apps/api/src/modules/import-export/service.ts@@ -1,14 +1,16 @@-import { db, importJob, importRecord } from '@repo/db';+import { db, importJob, importRecord, type ImportSource } from '@repo/db';import { desc, eq, sql } from 'drizzle-orm';import { encryptSecret } from '@repo/crypto';import { HttpError, iso } from '#shared/lib';import { pinnedFetch } from '#shared/net';+import { linearJobFields, type CreateLinearImportJobInput } from './linear';-// Data access and the Plane connection check for import jobs. Creating a job only-// encrypts and stores the submitted credential and leaves the row 'pending' for the-// worker (apps/worker/src/import-worker.ts) to pick up and drive through its phases —-// this module never talks to the worker or reads the credential back. Progress is-// read from import_record, the worker's own source-id-to-local-id mapping table.+// Data access and the Plane connection check for import jobs (Linear's is in+// linear.ts). Creating a job only encrypts and stores the submitted credential and+// leaves the row 'pending' for the worker (apps/worker/src/import-worker.ts) to pick+// up and drive through its phases — this module never talks to the worker or reads+// the credential back. Progress is read from import_record, the worker's own+// source-id-to-local-id mapping table.// Mirrors import_record_source_entity_type_check in packages/db/src/schema/app.ts.export const IMPORT_ENTITY_TYPES = [@@ -34,7 +36,7 @@ interface EntityCount {export interface ImportJobDto {id: number;projectId: number;- source: 'plane';+ source: ImportSource;phase: ImportJobPhase;status: ImportJobStatus;counts: Record<ImportEntityType, EntityCount>;@@ -72,7 +74,7 @@ function toDto(row: ImportJobRow, counts: Record<ImportEntityType, EntityCount>)return {id: row.id,projectId: row.projectId,- source: row.source as 'plane',+ source: row.source as ImportSource,phase: row.phase as ImportJobPhase,status: row.status as ImportJobStatus,counts,@@ -128,24 +130,25 @@ function normalizePlaneBaseUrl(raw: string): string {return url.origin;}-export interface CreateImportJobInput {+interface ImportJobChoices {+ unmatchedUserPolicy?: UnmatchedUserPolicy;+ stateOverrides?: Record<string, StateCategory>;+}++// A body without `source` is a Plane job, as before Linear existed.+export interface CreatePlaneImportJobInput {+ source?: 'plane';baseUrl: string;workspaceSlug: string;apiToken: string;planeProjectId: string;planeProjectKey: string;- unmatchedUserPolicy?: UnmatchedUserPolicy;- stateOverrides?: Record<string, StateCategory>;}-// Stores the submitted credential encrypted and leaves the job 'pending' — the-// worker picks it up on its next poll. The plaintext token exists only in this-// function's local variables; it is never persisted or logged.-export async function createImportJob(- projectId: number,- actorUserId: string,- input: CreateImportJobInput,-): Promise<ImportJobDto> {+export type CreateImportJobInput = ImportJobChoices &+ (CreatePlaneImportJobInput | CreateLinearImportJobInput);++function planeJobFields(input: CreatePlaneImportJobInput) {const baseUrl = normalizePlaneBaseUrl(input.baseUrl);const workspaceSlug = input.workspaceSlug.trim();const apiToken = input.apiToken.trim();@@ -155,23 +158,37 @@ export async function createImportJob(if (!apiToken) throw new HttpError(400, 'apiToken is required');if (!planeProjectId) throw new HttpError(400, 'planeProjectId is required');if (!planeProjectKey) throw new HttpError(400, 'planeProjectKey is required');-- const encrypted = encryptSecret(JSON.stringify({ baseUrl, workspaceSlug, apiKey: apiToken }));- const config = {- planeProjectId,- planeProjectKey,- unmatchedUserPolicy: input.unmatchedUserPolicy ?? 'unassigned',- ...(input.stateOverrides && Object.keys(input.stateOverrides).length > 0- ? { stateOverrides: input.stateOverrides }- : {}),+ return {+ source: 'plane' as const,+ credential: { baseUrl, workspaceSlug, apiKey: apiToken },+ config: { planeProjectId, planeProjectKey },};+}++// Stores the submitted credential encrypted and leaves the job 'pending' — the+// worker picks it up on its next poll. The plaintext token exists only in this+// function's local variables; it is never persisted or logged.+export async function createImportJob(+ projectId: number,+ actorUserId: string,+ input: CreateImportJobInput,+): Promise<ImportJobDto> {+ const { source, credential, config } =+ input.source === 'linear' ? linearJobFields(input) : planeJobFields(input);+ const encrypted = encryptSecret(JSON.stringify(credential));const [row] = await db.insert(importJob).values({projectId,createdByUserId: actorUserId,- source: 'plane',- config,+ source,+ config: {+ ...config,+ unmatchedUserPolicy: input.unmatchedUserPolicy ?? 'unassigned',+ ...(input.stateOverrides && Object.keys(input.stateOverrides).length > 0+ ? { stateOverrides: input.stateOverrides }+ : {}),+ },credentialCiphertext: encrypted.ciphertext,credentialIv: encrypted.iv,credentialAuthTag: encrypted.authTag,diff --git a/apps/web/messages/ar/settings.json b/apps/web/messages/ar/settings.jsonindex 9c6cfea6..5205ac13 100644--- a/apps/web/messages/ar/settings.json+++ b/apps/web/messages/ar/settings.json@@ -502,7 +502,7 @@"jobs": "مهام الاستيراد","jobsHint": "كل مهمة بتشتغل في الخلفية، وتقدر توقفها مؤقتًا أو تكمّلها أو تلغيها وهي شغالة.","emptyTitle": "مافيش عمليات استيراد لسه",- "emptyHint": "اتصل بنسخة Plane فوق وابدأ استيراد عشان تجيب مهامها.",+ "emptyHint": "اتصل بمصدر أعلاه وابدأ عملية استيراد لجلب مهامه.","export": "التصدير","exportHint": "نزّل نسخة كاملة من حالات وليبلز ودورات وتذاكر المشروع ده كـ JSON.","exportProjectData": "صدّر بيانات المشروع",@@ -512,8 +512,22 @@"cancel": "إلغاء","countsLegend": "اتعمل / اتلاقى","countsNotDiscovered": "لم يتم اكتشافها بعد",- "rateLimitedRetrying": "تم الوصول إلى حد معدل الطلبات في Plane. ستتم إعادة المحاولة خلال {seconds} ثانية.",+ "rateLimitedRetrying": "تم الوصول إلى حد معدل الطلبات في المصدر. ستتم إعادة المحاولة خلال {seconds} ثانية.","transientErrorRetrying": "{error} — ستتم إعادة المحاولة خلال {seconds} ثانية.",+ "linear": {+ "connect": "الاتصال بـ Linear",+ "connectHint": "أدخل مفتاح API الشخصي الخاص بـ Linear للتحقق منه وتحميل الفرق والمشاريع التي يمكنه الوصول إليها.",+ "apiKey": "مفتاح API",+ "apiKeyHint": "أنشئ مفتاحًا في Linear من Settings → Security & access → Personal API keys. تكفي صلاحية القراءة فقط.",+ "scope": "ما الذي تريد استيراده",+ "scopeHint": "اختر فريقًا، ثم أحد مشاريعه أو مهام الفريق التي لا تتبع أي مشروع. تُستورد المهام المؤرشفة أيضًا.",+ "team": "الفريق",+ "teamPlaceholder": "اختر فريقًا",+ "project": "المشروع",+ "projectPlaceholder": "اختر مشروعًا",+ "noProject": "مهام بلا مشروع",+ "noTeams": "لا يمكن لمفتاح API هذا الوصول إلى أي فريق."+ },"statuses": {"pending": "قيد الانتظار","running": "شغّال",diff --git a/apps/web/messages/en/settings.json b/apps/web/messages/en/settings.jsonindex b3b4d93e..c199a8a1 100644--- a/apps/web/messages/en/settings.json+++ b/apps/web/messages/en/settings.json@@ -502,7 +502,7 @@"jobs": "Import jobs","jobsHint": "Each job runs in the background and can be paused, resumed, or canceled while it is in progress.","emptyTitle": "No imports yet",- "emptyHint": "Connect to a Plane instance above and start an import to bring in its issues.",+ "emptyHint": "Connect to a source above and start an import to bring in its issues.","export": "Export","exportHint": "Download a self-contained snapshot of this project's states, labels, cycles, and issues as JSON.","exportProjectData": "Export project data",@@ -512,8 +512,22 @@"cancel": "Cancel","countsLegend": "created / discovered","countsNotDiscovered": "not yet discovered",- "rateLimitedRetrying": "Plane's rate limit was reached. Retrying in {seconds}s.",+ "rateLimitedRetrying": "The source's rate limit was reached. Retrying in {seconds}s.","transientErrorRetrying": "{error} — retrying in {seconds}s.",+ "linear": {+ "connect": "Connect to Linear",+ "connectHint": "Enter a Linear personal API key to check it and load the teams and projects it can see.",+ "apiKey": "API key",+ "apiKeyHint": "Create one in Linear under Settings → Security & access → Personal API keys. Read-only access is enough.",+ "scope": "What to import",+ "scopeHint": "Pick a team, then one of its projects or the team's issues that belong to no project. Archived issues are included.",+ "team": "Team",+ "teamPlaceholder": "Select a team",+ "project": "Project",+ "projectPlaceholder": "Select a project",+ "noProject": "Issues with no project",+ "noTeams": "This API key can't see any teams."+ },"statuses": {"pending": "Pending","running": "Running",diff --git a/apps/web/messages/es-ES/settings.json b/apps/web/messages/es-ES/settings.jsonindex 68c6acb5..b45c2279 100644--- a/apps/web/messages/es-ES/settings.json+++ b/apps/web/messages/es-ES/settings.json@@ -502,7 +502,7 @@"jobs": "Trabajos de importación","jobsHint": "Cada trabajo se ejecuta en segundo plano y se puede pausar, reanudar o cancelar mientras está en curso.","emptyTitle": "Aún no hay importaciones",- "emptyHint": "Conéctate a una instancia de Plane arriba e inicia una importación para traer sus tickets.",+ "emptyHint": "Conéctate a un origen arriba e inicia una importación para traer sus tickets.","export": "Exportar","exportHint": "Descarga una instantánea autocontenida de los estados, etiquetas, ciclos y tickets de este proyecto como JSON.","exportProjectData": "Exportar datos del proyecto",@@ -512,8 +512,22 @@"cancel": "Cancelar","countsLegend": "creados / detectados","countsNotDiscovered": "aún no detectados",- "rateLimitedRetrying": "Se alcanzó el límite de peticiones de Plane. Reintentando en {seconds}s.",+ "rateLimitedRetrying": "Se alcanzó el límite de peticiones del origen. Reintentando en {seconds}s.","transientErrorRetrying": "{error} — reintentando en {seconds}s.",+ "linear": {+ "connect": "Conectar con Linear",+ "connectHint": "Introduce una clave de API personal de Linear para comprobarla y cargar los equipos y proyectos que puede ver.",+ "apiKey": "Clave de API",+ "apiKeyHint": "Créala en Linear, en Settings → Security & access → Personal API keys. Basta con acceso de solo lectura.",+ "scope": "Qué importar",+ "scopeHint": "Elige un equipo y, después, uno de sus proyectos o los tickets del equipo que no pertenecen a ningún proyecto. También se importan los tickets archivados.",+ "team": "Equipo",+ "teamPlaceholder": "Selecciona un equipo",+ "project": "Proyecto",+ "projectPlaceholder": "Selecciona un proyecto",+ "noProject": "Tickets sin proyecto",+ "noTeams": "Esta clave de API no ve ningún equipo."+ },"statuses": {"pending": "Pendiente","running": "En ejecución",diff --git a/apps/web/messages/fr/settings.json b/apps/web/messages/fr/settings.jsonindex 24d1db73..b84fd638 100644--- a/apps/web/messages/fr/settings.json+++ b/apps/web/messages/fr/settings.json@@ -502,7 +502,7 @@"jobs": "Imports","jobsHint": "Chaque import s'exécute en arrière-plan et peut être mis en pause, repris ou annulé pendant son exécution.","emptyTitle": "Aucun import pour l'instant",- "emptyHint": "Connectez-vous à une instance Plane ci-dessus et démarrez un import pour récupérer ses tickets.",+ "emptyHint": "Connectez-vous à une source ci-dessus et démarrez un import pour récupérer ses tickets.","export": "Export","exportHint": "Téléchargez un instantané autonome des états, étiquettes, cycles et tickets de ce projet au format JSON.","exportProjectData": "Exporter les données du projet",@@ -512,8 +512,22 @@"cancel": "Annuler","countsLegend": "créés / trouvés","countsNotDiscovered": "pas encore découvert",- "rateLimitedRetrying": "La limite de requêtes de Plane a été atteinte. Nouvel essai dans {seconds} s.",+ "rateLimitedRetrying": "La limite de requêtes de la source a été atteinte. Nouvel essai dans {seconds} s.","transientErrorRetrying": "{error} — nouvel essai dans {seconds} s.",+ "linear": {+ "connect": "Se connecter à Linear",+ "connectHint": "Indiquez une clé API personnelle Linear pour la vérifier et charger les équipes et projets auxquels elle a accès.",+ "apiKey": "Clé API",+ "apiKeyHint": "Créez-la dans Linear, sous Settings → Security & access → Personal API keys. Un accès en lecture seule suffit.",+ "scope": "Contenu à importer",+ "scopeHint": "Choisissez une équipe, puis l'un de ses projets ou les tickets de l'équipe qui n'appartiennent à aucun projet. Les tickets archivés sont inclus.",+ "team": "Équipe",+ "teamPlaceholder": "Sélectionner une équipe",+ "project": "Projet",+ "projectPlaceholder": "Sélectionner un projet",+ "noProject": "Tickets sans projet",+ "noTeams": "Cette clé API ne voit aucune équipe."+ },"statuses": {"pending": "En attente","running": "En cours",diff --git a/apps/web/messages/id/settings.json b/apps/web/messages/id/settings.jsonindex 222e3de4..83734582 100644--- a/apps/web/messages/id/settings.json+++ b/apps/web/messages/id/settings.json@@ -502,7 +502,7 @@"jobs": "Tugas impor","jobsHint": "Setiap tugas berjalan di latar belakang dan bisa dijeda, dilanjutkan, atau dibatalkan selama masih berlangsung.","emptyTitle": "Belum ada impor",- "emptyHint": "Hubungkan ke instans Plane di atas dan mulai impor untuk mengambil issue-nya.",+ "emptyHint": "Hubungkan ke sumber di atas dan mulai impor untuk mengambil issue-nya.","export": "Ekspor","exportHint": "Unduh snapshot mandiri dari status, label, siklus, dan isu proyek ini sebagai JSON.","exportProjectData": "Ekspor data proyek",@@ -512,8 +512,22 @@"cancel": "Batal","countsLegend": "dibuat / ditemukan","countsNotDiscovered": "belum ditemukan",- "rateLimitedRetrying": "Batas laju permintaan Plane tercapai. Mencoba lagi dalam {seconds} dtk.",+ "rateLimitedRetrying": "Batas laju permintaan sumber tercapai. Mencoba lagi dalam {seconds} dtk.","transientErrorRetrying": "{error} — mencoba lagi dalam {seconds} dtk.",+ "linear": {+ "connect": "Hubungkan ke Linear",+ "connectHint": "Masukkan kunci API pribadi Linear untuk memeriksanya dan memuat tim serta proyek yang dapat dilihatnya.",+ "apiKey": "Kunci API",+ "apiKeyHint": "Buat di Linear melalui Settings → Security & access → Personal API keys. Akses baca saja sudah cukup.",+ "scope": "Yang diimpor",+ "scopeHint": "Pilih tim, lalu salah satu proyeknya atau issue tim yang tidak termasuk proyek mana pun. Issue yang diarsipkan juga diimpor.",+ "team": "Tim",+ "teamPlaceholder": "Pilih tim",+ "project": "Proyek",+ "projectPlaceholder": "Pilih proyek",+ "noProject": "Issue tanpa proyek",+ "noTeams": "Kunci API ini tidak dapat melihat tim mana pun."+ },"statuses": {"pending": "Tertunda","running": "Berjalan",diff --git a/apps/web/messages/pt-BR/settings.json b/apps/web/messages/pt-BR/settings.jsonindex 5e59ca3e..38087b5e 100644--- a/apps/web/messages/pt-BR/settings.json+++ b/apps/web/messages/pt-BR/settings.json@@ -502,7 +502,7 @@"jobs": "Importações","jobsHint": "Cada importação roda em segundo plano e pode ser pausada, retomada ou cancelada enquanto estiver em andamento.","emptyTitle": "Nenhuma importação ainda",- "emptyHint": "Conecte-se a uma instância Plane acima e inicie uma importação para trazer suas issues.",+ "emptyHint": "Conecte-se a uma origem acima e inicie uma importação para trazer suas issues.","export": "Exportar","exportHint": "Baixe um snapshot autocontido dos estados, etiquetas, ciclos e itens deste projeto em JSON.","exportProjectData": "Exportar dados do projeto",@@ -512,8 +512,22 @@"cancel": "Cancelar","countsLegend": "criados / encontrados","countsNotDiscovered": "ainda não descoberto",- "rateLimitedRetrying": "O limite de requisições do Plane foi atingido. Tentando novamente em {seconds}s.",+ "rateLimitedRetrying": "O limite de requisições da origem foi atingido. Tentando novamente em {seconds}s.","transientErrorRetrying": "{error} — tentando novamente em {seconds}s.",+ "linear": {+ "connect": "Conectar ao Linear",+ "connectHint": "Informe uma chave de API pessoal do Linear para verificá-la e carregar os times e projetos que ela pode ver.",+ "apiKey": "Chave de API",+ "apiKeyHint": "Crie uma no Linear em Settings → Security & access → Personal API keys. Acesso somente leitura é suficiente.",+ "scope": "O que importar",+ "scopeHint": "Escolha um time e depois um dos projetos dele ou as issues do time que não pertencem a nenhum projeto. Issues arquivadas também são importadas.",+ "team": "Time",+ "teamPlaceholder": "Selecione um time",+ "project": "Projeto",+ "projectPlaceholder": "Selecione um projeto",+ "noProject": "Issues sem projeto",+ "noTeams": "Esta chave de API não vê nenhum time."+ },"statuses": {"pending": "Pendente","running": "Em execução",diff --git a/apps/web/messages/ru/settings.json b/apps/web/messages/ru/settings.jsonindex 05adbdb0..c334f7a5 100644--- a/apps/web/messages/ru/settings.json+++ b/apps/web/messages/ru/settings.json@@ -502,7 +502,7 @@"jobs": "Задачи импорта","jobsHint": "Каждая задача выполняется в фоне, и пока она не завершена, её можно приостановить, возобновить или отменить.","emptyTitle": "Импортов пока нет",- "emptyHint": "Подключитесь к инстансу Plane выше и запустите импорт, чтобы перенести его задачи.",+ "emptyHint": "Подключитесь к источнику выше и запустите импорт, чтобы перенести его задачи.","export": "Экспорт","exportHint": "Скачайте автономный снимок статусов, меток, циклов и задач этого проекта в формате JSON.","exportProjectData": "Экспортировать данные проекта",@@ -512,8 +512,22 @@"cancel": "Отменить","countsLegend": "создано / найдено","countsNotDiscovered": "пока не обнаружено",- "rateLimitedRetrying": "Достигнут лимит запросов Plane. Повтор через {seconds} с.",+ "rateLimitedRetrying": "Достигнут лимит запросов источника. Повтор через {seconds} с.","transientErrorRetrying": "{error} — повтор через {seconds} с.",+ "linear": {+ "connect": "Подключение к Linear",+ "connectHint": "Укажите личный API-ключ Linear, чтобы проверить его и загрузить команды и проекты, к которым у него есть доступ.",+ "apiKey": "API-ключ",+ "apiKeyHint": "Создайте его в Linear: Settings → Security & access → Personal API keys. Достаточно доступа только на чтение.",+ "scope": "Что импортировать",+ "scopeHint": "Выберите команду, затем один из её проектов или задачи команды, не относящиеся ни к одному проекту. Архивные задачи тоже импортируются.",+ "team": "Команда",+ "teamPlaceholder": "Выберите команду",+ "project": "Проект",+ "projectPlaceholder": "Выберите проект",+ "noProject": "Задачи без проекта",+ "noTeams": "Этот API-ключ не видит ни одной команды."+ },"statuses": {"pending": "В ожидании","running": "Выполняется",diff --git a/apps/web/messages/uk/settings.json b/apps/web/messages/uk/settings.jsonindex b080bc4c..4acfcd32 100644--- a/apps/web/messages/uk/settings.json+++ b/apps/web/messages/uk/settings.json@@ -502,7 +502,7 @@"jobs": "Завдання імпорту","jobsHint": "Кожне завдання виконується у фоні, і поки воно не завершене, його можна призупинити, відновити або скасувати.","emptyTitle": "Імпортів ще немає",- "emptyHint": "Підключіться до інстансу Plane вище і почніть імпорт, щоб перенести його задачі.",+ "emptyHint": "Підключіться до джерела вище і почніть імпорт, щоб перенести його задачі.","export": "Експорт","exportHint": "Завантажте автономний знімок станів, міток, циклів і задач цього проєкту у форматі JSON.","exportProjectData": "Експортувати дані проєкту",@@ -512,8 +512,22 @@"cancel": "Скасувати","countsLegend": "створено / знайдено","countsNotDiscovered": "ще не знайдено",- "rateLimitedRetrying": "Досягнуто ліміту запитів Plane. Повтор через {seconds} с.",+ "rateLimitedRetrying": "Досягнуто ліміту запитів джерела. Повтор через {seconds} с.","transientErrorRetrying": "{error} — повтор через {seconds} с.",+ "linear": {+ "connect": "Підключення до Linear",+ "connectHint": "Вкажіть особистий API-ключ Linear, щоб перевірити його та завантажити команди й проєкти, до яких він має доступ.",+ "apiKey": "API-ключ",+ "apiKeyHint": "Створіть його в Linear: Settings → Security & access → Personal API keys. Достатньо доступу лише на читання.",+ "scope": "Що імпортувати",+ "scopeHint": "Виберіть команду, а потім один із її проєктів або задачі команди, що не належать до жодного проєкту. Архівні задачі теж імпортуються.",+ "team": "Команда",+ "teamPlaceholder": "Виберіть команду",+ "project": "Проєкт",+ "projectPlaceholder": "Виберіть проєкт",+ "noProject": "Задачі без проєкту",+ "noTeams": "Цей API-ключ не бачить жодної команди."+ },"statuses": {"pending": "В очікуванні","running": "Виконується",diff --git a/apps/web/messages/zh-CN/settings.json b/apps/web/messages/zh-CN/settings.jsonindex c5ba9dff..b3ce57fe 100644--- a/apps/web/messages/zh-CN/settings.json+++ b/apps/web/messages/zh-CN/settings.json@@ -502,7 +502,7 @@"jobs": "导入任务","jobsHint": "每个任务都在后台运行,进行中可以暂停、继续或取消。","emptyTitle": "暂无导入记录",- "emptyHint": "在上方连接 Plane 实例并开始导入,以引入其工作项。",+ "emptyHint": "在上方连接一个来源并开始导入,以引入其工作项。","export": "导出","exportHint": "下载该项目状态、标签、周期和任务的独立 JSON 快照。","exportProjectData": "导出项目数据",@@ -512,8 +512,22 @@"cancel": "取消","countsLegend": "已创建 / 已发现","countsNotDiscovered": "尚未发现",- "rateLimitedRetrying": "已达到 Plane 的速率限制,将在 {seconds} 秒后重试。",+ "rateLimitedRetrying": "已达到来源的速率限制,将在 {seconds} 秒后重试。","transientErrorRetrying": "{error} — 将在 {seconds} 秒后重试。",+ "linear": {+ "connect": "连接 Linear",+ "connectHint": "输入 Linear 个人 API 密钥以检查它,并加载它可以访问的团队和项目。",+ "apiKey": "API 密钥",+ "apiKeyHint": "在 Linear 的 Settings → Security & access → Personal API keys 中创建。只读权限即可。",+ "scope": "导入内容",+ "scopeHint": "选择一个团队,然后选择它的一个项目,或该团队中不属于任何项目的工作项。已归档的工作项也会导入。",+ "team": "团队",+ "teamPlaceholder": "选择一个团队",+ "project": "项目",+ "projectPlaceholder": "选择一个项目",+ "noProject": "无项目的工作项",+ "noTeams": "此 API 密钥看不到任何团队。"+ },"statuses": {"pending": "待处理","running": "运行中",diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExport.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExport.tsxindex ef77a7f2..d7895723 100644--- a/apps/web/src/features/settings/components/import-export/SettingsImportExport.tsx+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExport.tsx@@ -1,7 +1,11 @@import { useState } from 'react';import { useTranslations } from 'next-intl';import type { ProjectDetail } from '@/lib/api/endpoints/projects';-import type { PlaneConnectionInput, PlaneProjectOption } from '@/lib/api/endpoints/importExport';+import type {+ ImportSource,+ PlaneConnectionInput,+ PlaneProjectOption,+} from '@/lib/api/endpoints/importExport';import { usePermissions } from '@/hooks/usePermissions';import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';import SettingsCard from '@/components/common/page/SettingsCard';@@ -11,15 +15,16 @@ import SettingsImportExportProjectPicker from './SettingsImportExportProjectPickimport SettingsImportExportMappingReview from './SettingsImportExportMappingReview';import SettingsImportExportJobList from './SettingsImportExportJobList';import SettingsImportExportDownloadButton from './SettingsImportExportDownloadButton';+import SettingsImportExportLinear from './SettingsImportExportLinear';export interface PlaneConnection extends PlaneConnectionInput {projects: PlaneProjectOption[];}-// Plane is the only source that imports today; the rest are listed disabled.+// Plane and Linear import today; the rest are listed disabled.const SOURCES = [{ key: 'plane', label: 'Plane', available: true },- { key: 'linear', label: 'Linear', available: false },+ { key: 'linear', label: 'Linear', available: true },{ key: 'jira', label: 'Jira', available: false },{ key: 'trello', label: 'Trello', available: false },] as const;@@ -35,6 +40,7 @@ export default function SettingsImportExport({ project }: { project: ProjectDetaconst { can } = usePermissions();const canCreate = can('import_export', 'create');const canEdit = can('import_export', 'edit');+ const [source, setSource] = useState<ImportSource>('plane');const [connection, setConnection] = useState<PlaneConnection | null>(null);const [selected, setSelected] = useState<PlaneProjectOption | null>(null);@@ -53,12 +59,12 @@ export default function SettingsImportExport({ project }: { project: ProjectDeta{canCreate && (<><SettingsSection title={t('source')} description={t('sourceHint')}>- <Tabs value="plane">+ <Tabs value={source} onValueChange={(value) => setSource(value as ImportSource)}><TabsList variant="line">- {SOURCES.map((source) => (- <TabsTrigger key={source.key} value={source.key} disabled={!source.available}>- {source.label}- {!source.available && (+ {SOURCES.map((option) => (+ <TabsTrigger key={option.key} value={option.key} disabled={!option.available}>+ {option.label}+ {!option.available && (<span className="text-[10px] font-normal tracking-wide uppercase">{t('comingSoon')}</span>@@ -68,31 +74,35 @@ export default function SettingsImportExport({ project }: { project: ProjectDeta</TabsList></Tabs></SettingsSection>- <SettingsSection title={t('connect')} description={t('connectHint')}>- <SettingsCard className="p-4">- <SettingsImportExportConnectForm projectKey={projectKey} onTested={onTested} />- </SettingsCard>- </SettingsSection>- {connection && (- <SettingsSection title={t('sourceProject')} description={t('sourceProjectHint')}>- <SettingsCard className="space-y-6 p-4">- <SettingsImportExportProjectPicker- key={connection.baseUrl + connection.workspaceSlug}- connection={connection}- selected={selected}- onSelect={setSelected}- />- {selected && (- <SettingsImportExportMappingReview- projectKey={projectKey}- connection={connection}- selected={selected}- onImported={() => setSelected(null)}- />- )}- </SettingsCard>- </SettingsSection>+ {source === 'plane' && (+ <>+ <SettingsSection title={t('connect')} description={t('connectHint')}>+ <SettingsCard className="p-4">+ <SettingsImportExportConnectForm projectKey={projectKey} onTested={onTested} />+ </SettingsCard>+ </SettingsSection>+ {connection && (+ <SettingsSection title={t('sourceProject')} description={t('sourceProjectHint')}>+ <SettingsCard className="space-y-6 p-4">+ <SettingsImportExportProjectPicker+ key={connection.baseUrl + connection.workspaceSlug}+ connection={connection}+ selected={selected}+ onSelect={setSelected}+ />+ {selected && (+ <SettingsImportExportMappingReview+ projectKey={projectKey}+ target={{ source: 'plane', connection, project: selected }}+ onImported={() => setSelected(null)}+ />+ )}+ </SettingsCard>+ </SettingsSection>+ )}+ </>)}+ {source === 'linear' && <SettingsImportExportLinear projectKey={projectKey} />}</>)}<SettingsSection title={t('jobs')} description={t('jobsHint')}>diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportLinear.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportLinear.tsxnew file mode 100644index 00000000..94421895--- /dev/null+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportLinear.tsx@@ -0,0 +1,71 @@+import { useState } from 'react';+import { useTranslations } from 'next-intl';+import type { LinearTeamOption } from '@/lib/api/endpoints/importExport';+import SettingsCard from '@/components/common/page/SettingsCard';+import SettingsSection from '@/components/common/page/SettingsSection';+import SettingsImportExportLinearConnectForm from './SettingsImportExportLinearConnectForm';+import SettingsImportExportLinearScopePicker, {+ NO_PROJECT,+} from './SettingsImportExportLinearScopePicker';+import SettingsImportExportMappingReview from './SettingsImportExportMappingReview';++export interface LinearConnection {+ apiToken: string;+ teams: LinearTeamOption[];+}++// The Linear source on the Import tab: check an API key, pick a team and one of its+// projects (or its issues with no project), review the state mapping, start the job.+export default function SettingsImportExportLinear({ projectKey }: { projectKey: string }) {+ const t = useTranslations('settings.importExport');+ const [connection, setConnection] = useState<LinearConnection | null>(null);+ const [team, setTeam] = useState<LinearTeamOption | null>(null);+ const [projectChoice, setProjectChoice] = useState<string | null>(null);++ function onTested(next: LinearConnection) {+ setConnection(next);+ setTeam(null);+ setProjectChoice(null);+ }++ function onTeamChange(next: LinearTeamOption | null) {+ setTeam(next);+ setProjectChoice(null);+ }++ return (+ <>+ <SettingsSection title={t('linear.connect')} description={t('linear.connectHint')}>+ <SettingsCard className="p-4">+ <SettingsImportExportLinearConnectForm projectKey={projectKey} onTested={onTested} />+ </SettingsCard>+ </SettingsSection>+ {connection && (+ <SettingsSection title={t('linear.scope')} description={t('linear.scopeHint')}>+ <SettingsCard className="space-y-6 p-4">+ <SettingsImportExportLinearScopePicker+ teams={connection.teams}+ team={team}+ projectChoice={projectChoice}+ onTeamChange={onTeamChange}+ onProjectChoiceChange={setProjectChoice}+ />+ {team && projectChoice && (+ <SettingsImportExportMappingReview+ key={`${team.id}:${projectChoice}`}+ projectKey={projectKey}+ target={{+ source: 'linear',+ apiToken: connection.apiToken,+ team,+ projectId: projectChoice === NO_PROJECT ? null : projectChoice,+ }}+ onImported={() => setProjectChoice(null)}+ />+ )}+ </SettingsCard>+ </SettingsSection>+ )}+ </>+ );+}diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportLinearConnectForm.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportLinearConnectForm.tsxnew file mode 100644index 00000000..e7e9d2e9--- /dev/null+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportLinearConnectForm.tsx@@ -0,0 +1,56 @@+import { useState, type FormEvent } from 'react';+import { useTranslations } from 'next-intl';+import { useTestLinearConnection } from '../../services/settings.service';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import type { LinearConnection } from './SettingsImportExportLinear';++// A Linear personal API key, checked live against Linear. Nothing is stored until+// an import is actually started.+export default function SettingsImportExportLinearConnectForm({+ projectKey,+ onTested,+}: {+ projectKey: string;+ onTested: (connection: LinearConnection) => void;+}) {+ const t = useTranslations('settings.importExport');+ const testConnection = useTestLinearConnection(projectKey);+ const [apiToken, setApiToken] = useState('');++ async function submit(event: FormEvent<HTMLFormElement>) {+ event.preventDefault();+ const input = { apiToken: apiToken.trim() };+ try {+ const result = await testConnection.mutateAsync(input);+ onTested({ ...input, teams: result.teams });+ } catch {+ // Surfaced by the global mutation error toast; nothing local to do.+ }+ }++ return (+ <form+ onSubmit={(event) => void submit(event)}+ autoComplete="off"+ className="max-w-md space-y-4"+ >+ <div className="space-y-1.5">+ <Label htmlFor="linear-api-key">{t('linear.apiKey')}</Label>+ <Input+ id="linear-api-key"+ type="password"+ autoComplete="off"+ value={apiToken}+ onChange={(event) => setApiToken(event.target.value)}+ required+ />+ <p className="text-xs text-muted-foreground">{t('linear.apiKeyHint')}</p>+ </div>+ <Button type="submit" disabled={testConnection.isPending || apiToken.trim() === ''}>+ {testConnection.isPending ? t('testing') : t('testConnection')}+ </Button>+ </form>+ );+}diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportLinearScopePicker.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportLinearScopePicker.tsxnew file mode 100644index 00000000..d1ed854d--- /dev/null+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportLinearScopePicker.tsx@@ -0,0 +1,77 @@+import { useTranslations } from 'next-intl';+import { Label } from '@/components/ui/label';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import type { LinearTeamOption } from '@/lib/api/endpoints/importExport';++// The project choice for the team's issues that belong to no project. Linear ids+// are UUIDs, so it never collides with one.+export const NO_PROJECT = 'no-project';++// The teams the tested key can see, then one project of the picked team or its+// issues with no project. This component only picks; the parent shows the review.+export default function SettingsImportExportLinearScopePicker({+ teams,+ team,+ projectChoice,+ onTeamChange,+ onProjectChoiceChange,+}: {+ teams: LinearTeamOption[];+ team: LinearTeamOption | null;+ projectChoice: string | null;+ onTeamChange: (team: LinearTeamOption | null) => void;+ onProjectChoiceChange: (choice: string) => void;+}) {+ const t = useTranslations('settings.importExport');++ if (teams.length === 0) {+ return <p className="text-sm text-muted-foreground">{t('linear.noTeams')}</p>;+ }++ return (+ <div className="flex flex-wrap gap-4">+ <div className="w-64 space-y-1.5">+ <Label htmlFor="linear-team">{t('linear.team')}</Label>+ <Select+ value={team?.id ?? ''}+ onValueChange={(id) => onTeamChange(teams.find((option) => option.id === id) ?? null)}+ >+ <SelectTrigger id="linear-team" className="w-full">+ <SelectValue placeholder={t('linear.teamPlaceholder')} />+ </SelectTrigger>+ <SelectContent>+ {teams.map((option) => (+ <SelectItem key={option.id} value={option.id}>+ {option.name} ({option.key})+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ {team && (+ <div className="w-64 space-y-1.5">+ <Label htmlFor="linear-project">{t('linear.project')}</Label>+ <Select value={projectChoice ?? ''} onValueChange={onProjectChoiceChange}>+ <SelectTrigger id="linear-project" className="w-full">+ <SelectValue placeholder={t('linear.projectPlaceholder')} />+ </SelectTrigger>+ <SelectContent>+ {team.projects.map((project) => (+ <SelectItem key={project.id} value={project.id}>+ {project.name}+ </SelectItem>+ ))}+ <SelectItem value={NO_PROJECT}>{t('linear.noProject')}</SelectItem>+ </SelectContent>+ </Select>+ </div>+ )}+ </div>+ );+}diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportMappingReview.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportMappingReview.tsxindex 07139aca..ac190bb5 100644--- a/apps/web/src/features/settings/components/import-export/SettingsImportExportMappingReview.tsx+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportMappingReview.tsx@@ -3,7 +3,11 @@import { useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { useCreateImportJob, useTestPlaneStatesPreview } from '../../services/settings.service';+import {+ useCreateImportJob,+ useTestLinearStatesPreview,+ useTestPlaneStatesPreview,+} from '../../services/settings.service';import { Button } from '@/components/ui/button';import { Label } from '@/components/ui/label';import {@@ -17,34 +21,68 @@ import SettingsCard from '@/components/common/page/SettingsCard';import ListSkeleton from '@/components/common/skeleton/ListSkeleton';import SettingsImportExportStateOverrideRow from './SettingsImportExportStateOverrideRow';import type {+ LinearImportJobFields,+ LinearTeamOption,+ PlaneConnectionInput,+ PlaneImportJobFields,PlaneProjectOption,StateCategory,UnmatchedUserPolicy,} from '@/lib/api/endpoints/importExport';-import type { PlaneConnection } from './SettingsImportExport';++// What is about to be imported: one Plane project, or one Linear team's project+// (projectId) or its issues with no project (projectId null).+export type ImportReviewTarget =+ | { source: 'plane'; connection: PlaneConnectionInput; project: PlaneProjectOption }+ | { source: 'linear'; apiToken: string; team: LinearTeamOption; projectId: string | null };++function jobFields(target: ImportReviewTarget): PlaneImportJobFields | LinearImportJobFields {+ if (target.source === 'plane') {+ return {+ source: 'plane',+ baseUrl: target.connection.baseUrl,+ workspaceSlug: target.connection.workspaceSlug,+ apiToken: target.connection.apiToken,+ planeProjectId: target.project.id,+ planeProjectKey: target.project.identifier,+ };+ }+ const team = { apiToken: target.apiToken, teamId: target.team.id, teamKey: target.team.key };+ return target.projectId+ ? { source: 'linear', ...team, projectFilter: 'project', projectId: target.projectId }+ : { source: 'linear', ...team, projectFilter: 'none' };+}// Shown once a source project is picked, before the job is created: the states-// Plane reports for it, each pre-filled with the category itsaplan would map it to-// automatically, and the unmatched-assignee/comment-author policy. Only a state row-// the user actually changes from its default is sent as an override.+// the source reports for it, each pre-filled with the category itsaplan would map it+// to automatically, and the unmatched-assignee/comment-author policy. Only a state+// row the user actually changes from its default is sent as an override.export default function SettingsImportExportMappingReview({projectKey,- connection,- selected,+ target,onImported,}: {projectKey: string;- connection: PlaneConnection;- selected: PlaneProjectOption;+ target: ImportReviewTarget;onImported: () => void;}) {const t = useTranslations('settings.importExport');- const preview = useTestPlaneStatesPreview(projectKey, {- baseUrl: connection.baseUrl,- workspaceSlug: connection.workspaceSlug,- apiToken: connection.apiToken,- planeProjectId: selected.id,- });+ const planePreview = useTestPlaneStatesPreview(+ projectKey,+ target.source === 'plane'+ ? {+ baseUrl: target.connection.baseUrl,+ workspaceSlug: target.connection.workspaceSlug,+ apiToken: target.connection.apiToken,+ planeProjectId: target.project.id,+ }+ : null,+ );+ const linearPreview = useTestLinearStatesPreview(+ projectKey,+ target.source === 'linear' ? { apiToken: target.apiToken, teamId: target.team.id } : null,+ );+ const preview = target.source === 'plane' ? planePreview : linearPreview;const createJob = useCreateImportJob(projectKey);const [overrides, setOverrides] = useState<Record<string, StateCategory>>({});const [unmatchedUserPolicy, setUnmatchedUserPolicy] = useState<UnmatchedUserPolicy>('unassigned');@@ -52,11 +90,7 @@ export default function SettingsImportExportMappingReview({async function start() {try {await createJob.mutateAsync({- baseUrl: connection.baseUrl,- workspaceSlug: connection.workspaceSlug,- apiToken: connection.apiToken,- planeProjectId: selected.id,- planeProjectKey: selected.identifier,+ ...jobFields(target),unmatchedUserPolicy,stateOverrides: overrides,});diff --git a/apps/web/src/features/settings/services/settings.service.ts b/apps/web/src/features/settings/services/settings.service.tsindex 77d519d2..cf5faf8a 100644--- a/apps/web/src/features/settings/services/settings.service.ts+++ b/apps/web/src/features/settings/services/settings.service.ts@@ -41,7 +41,10 @@ import {} from '@/lib/api/endpoints/git';import {type CreateImportJobInput,+ type LinearConnectionInput,type PlaneConnectionInput,+ testLinearConnection,+ testLinearStatesPreview,testPlaneConnection,testPlaneStatesPreview,createImportJob,@@ -271,8 +274,8 @@ export function useDisconnectGitRepository(projectKey: string, connectionId: num});}-// Import/export section: testing a connection to a source Plane instance,-// starting an import job, and tracking the ones already running.+// Import/export section: testing a connection to a source Plane instance or a+// Linear API key, starting an import job, and tracking the ones already running.export function useTestPlaneConnection(projectKey: string) {return useMutation({mutationFn: (input: PlaneConnectionInput) => testPlaneConnection(projectKey, input),@@ -293,6 +296,24 @@ export function useTestPlaneStatesPreview(});}+export function useTestLinearConnection(projectKey: string) {+ return useMutation({+ mutationFn: (input: LinearConnectionInput) => testLinearConnection(projectKey, input),+ });+}++// Fetched automatically once a Linear team is picked, in the mapping review step.+export function useTestLinearStatesPreview(+ projectKey: string,+ input: (LinearConnectionInput & { teamId: string }) | null,+) {+ return useQuery({+ queryKey: qk.linearPreview(projectKey, input?.teamId ?? 'none'),+ queryFn: () => testLinearStatesPreview(projectKey, input!),+ enabled: input != null,+ });+}+export function useCreateImportJob(projectKey: string) {const qc = useQueryClient();return useMutation({diff --git a/apps/web/src/lib/api/endpoints/importExport.ts b/apps/web/src/lib/api/endpoints/importExport.tsindex e9d8d78c..4199273c 100644--- a/apps/web/src/lib/api/endpoints/importExport.ts+++ b/apps/web/src/lib/api/endpoints/importExport.ts@@ -1,12 +1,14 @@import { request } from '@/lib/api/core/client';-// Import jobs bring issues in from a source Plane instance (mirrors apps/api-// modules/import-export/service.ts). Creating one stores an encrypted credential-// and leaves the job 'pending' for the worker to drive through its phases.+// Import jobs bring issues in from a Plane instance or a Linear workspace (mirrors+// apps/api modules/import-export/service.ts and linear.ts). Creating one stores an+// encrypted credential and leaves the job 'pending' for the worker to drive through+// its phases.export type ImportJobPhase = 'discover' | 'create' | 'link' | 'rewrite' | 'attachments' | 'done';export type ImportJobStatus = 'pending' | 'running' | 'paused' | 'completed' | 'failed';export type ImportEntityType = 'issue' | 'comment' | 'label' | 'state' | 'cycle' | 'attachment';+export type ImportSource = 'plane' | 'linear';export interface ImportEntityCount {discovered: number;@@ -16,7 +18,7 @@ export interface ImportEntityCount {export interface ImportJob {id: number;projectId: number;- source: 'plane';+ source: ImportSource;phase: ImportJobPhase;status: ImportJobStatus;counts: Record<ImportEntityType, ImportEntityCount>;@@ -47,13 +49,44 @@ export interface PlaneConnectionInput {apiToken: string;}-export interface CreateImportJobInput extends PlaneConnectionInput {- planeProjectId: string;- planeProjectKey: string;+export interface LinearProjectOption {+ id: string;+ name: string;+}++export interface LinearTeamOption {+ id: string;+ key: string;+ name: string;+ projects: LinearProjectOption[];+}++export interface LinearConnectionInput {+ apiToken: string;+}++export interface ImportJobChoices {unmatchedUserPolicy?: UnmatchedUserPolicy;stateOverrides?: Record<string, StateCategory>;}+export interface PlaneImportJobFields extends PlaneConnectionInput {+ source: 'plane';+ planeProjectId: string;+ planeProjectKey: string;+}++export interface LinearImportJobFields extends LinearConnectionInput {+ source: 'linear';+ teamId: string;+ teamKey: string;+ projectFilter: 'project' | 'none';+ projectId?: string;+}++export type CreateImportJobInput = ImportJobChoices &+ (PlaneImportJobFields | LinearImportJobFields);+export const testPlaneConnection = (projectKey: string, input: PlaneConnectionInput) =>request<{ projects: PlaneProjectOption[] }>(`/projects/${projectKey}/import-jobs/test-connection`,@@ -69,6 +102,21 @@ export const testPlaneStatesPreview = (body: JSON.stringify(input),});+export const testLinearConnection = (projectKey: string, input: LinearConnectionInput) =>+ request<{ teams: LinearTeamOption[] }>(+ `/projects/${projectKey}/import-jobs/linear-test-connection`,+ { method: 'POST', body: JSON.stringify(input) },+ );++export const testLinearStatesPreview = (+ projectKey: string,+ input: LinearConnectionInput & { teamId: string },+) =>+ request<{ states: PlaneStateOption[] }>(`/projects/${projectKey}/import-jobs/linear-preview`, {+ method: 'POST',+ body: JSON.stringify(input),+ });+export const createImportJob = (projectKey: string, input: CreateImportJobInput) =>request<ImportJob>(`/projects/${projectKey}/import-jobs`, {method: 'POST',diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex c224ca6c..321eaa80 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -70,11 +70,14 @@ export const qk = {actions: (projectKey: string) => ['actions', projectKey] as const,webhooks: (projectKey: string) => ['webhooks', projectKey] as const,webhookDeliveries: (webhookId: number) => ['webhookDeliveries', webhookId] as const,- // The project's Plane import jobs (the Import/Export settings section).+ // The project's import jobs (the Import/Export settings section).importJobs: (projectKey: string) => ['importJobs', projectKey] as const,// The mapping review preview for one candidate Plane project, before a job exists.planePreview: (projectKey: string, planeProjectId: string) =>['planePreview', projectKey, planeProjectId] as const,+ // The same preview for one Linear team's workflow states.+ linearPreview: (projectKey: string, teamId: string) =>+ ['linearPreview', projectKey, teamId] as const,// Saved dashboards (the analytics tabs) and the read-only metrics behind their// widgets. `kind` names the metric (stats/pulse/throughput/breakdown/...) and// `params` scopes it to the widget's query (window, filters).diff --git a/apps/worker/AGENTS.md b/apps/worker/AGENTS.mdindex 9f162ba1..d48da15c 100644--- a/apps/worker/AGENTS.md+++ b/apps/worker/AGENTS.md@@ -32,19 +32,28 @@ running to completion in one.- `canonical.ts` — the source-independent shape an adapter produces(`CanonicalIssue`, `CanonicalState`, ...). Plain types, no logic.- `reader.ts` — the `SourceReader` port a source adapter implements, and the- `SourceRateLimitedError` an adapter throws when the source's rate limit is reached.+ `SourceRateLimitedError` an adapter throws when the source's rate limit is+ reached.- `import-sources.ts` — one entry per `import_job.source`: its credential andconfig types, how to build its reader, and its issue-key prefix for Rewrite. Anew source adds an entry here; the phases do not change.- `import-retry.ts` — what a failed tick does: a rate limit is waited out and- does not count toward the attempt limit (the claim's bump is undone), any- other error retries with backoff until `MAX_ATTEMPTS` in a row.-- `plane-adapter.ts` — the only implementation today. HTTP against a Plane+ does not count toward the attempt limit (the claim's bump is undone), a job whose+ source has no registry entry fails at once, any other error retries with backoff+ until `MAX_ATTEMPTS` in a row.+- `plane-adapter.ts` — the Plane implementation. HTTP against a Planeinstance via `pinnedFetch`, using the credential decrypted from the job row(base URL, workspace slug, API key — never from env, since this has to workagainst any operator's self-hosted instance). `docs/dev/plane-import-source-notes.md`is the spec it follows for pagination, rate limiting, and Plane's actual wireshapes.+- `linear-adapter.ts` and `linear-mapping.ts` — the Linear implementation: its+ GraphQL API at the fixed `https://api.linear.app/graphql` with the job's+ personal API key, and the pure mapping from Linear's shapes. Issues in+ Linear's trash are left out. Files uploaded into Linear text are attachments;+ `resolveAttachmentDownload` follows `uploads.linear.app`'s redirects itself+ and sends the key to that host only. `docs/dev/linear-import.md` has the+ queries, limits and mapping.- `cross-reference.ts` — pure text matching for a source's own "KEY-123"-styleissue identifier: no `@repo/db`, no network, unit-tested directly. Whatthe Rewrite phase resolves into itsaplan's own issue ids.@@ -61,7 +70,9 @@ running to completion in one.chance to resolve, the same way it already does for relations. Rewrite scansevery created issue's description and comments for a mention of thesource's own identifier and rewrites it to this project's, purely from- already-local data — it makes no further requests to the source.+ already-local data — it makes no further requests to the source. An issue's+ mention of itself stays as written (the Linear footer relies on it), and so+ does an identifier that is a segment of a URL path.- The Attachments phase re-lists each issue's attachments (metadata alone,captured during Create, is not reused — a download needs a fresh resolve ofthe two-hop, hour-lived URL right before it happens) and downloads the@@ -73,9 +84,11 @@ running to completion in one.more inside the same advisory lock (`lockAttachmentStorage`) an interactiveupload takes, so the two never both pass a check that only one of them canactually fit. A download that answers anything but 2xx (an error page, a- redirect) is refused before its body is read (`attachment-download.ts`). A- rejected attachment (`AttachmentRejectedError`) is logged and skipped, not- treated as a failed tick.+ redirect) is refused before its body is read, and one that runs past the+ size limit is cut off there (`attachment-download.ts`): Linear reports no+ size, so that is its only size check. A rejected attachment+ (`AttachmentRejectedError`) is logged and skipped, not treated as a failed+ tick.## Invariants@@ -99,11 +112,12 @@ running to completion in one.- **Pure logic stays dependency-free.** `backoff.ts`, `signature.ts`, and`isRetryableStatus` import nothing from `@repo/db`, so unit tests run without adatabase. Keep DB access in `store.ts`. Same split for imports: `canonical.ts`,- `reader.ts`, `plane-adapter.ts`, `cross-reference.ts`, `attachment-download.ts`,- `import-sources.ts`, and `import-retry.ts` import nothing from- `@repo/db` (its state-category normalization, markdown conversion,- cursor/rate-limit, and cross-reference matching logic are unit-tested- directly); `@repo/db` access stays in `import-store.ts`.+ `reader.ts`, `plane-adapter.ts`, `linear-adapter.ts`, `linear-mapping.ts`,+ `cross-reference.ts`, `attachment-download.ts`, `import-sources.ts`, and+ `import-retry.ts` import nothing from `@repo/db` (their state-category+ normalization, markdown conversion, cursor/rate-limit, and cross-reference+ matching logic are unit-tested directly); `@repo/db` access stays in+ `import-store.ts`.- **An import job's credential is decrypted here, never routed through`packages/db/src/domains/`.** That directory is for config more than oneprocess reads; only the worker ever decrypts a stored import credential (thediff --git a/apps/worker/src/__tests__/integration/import-rewrite.test.ts b/apps/worker/src/__tests__/integration/import-rewrite.test.tsnew file mode 100644index 00000000..e341f3bd--- /dev/null+++ b/apps/worker/src/__tests__/integration/import-rewrite.test.ts@@ -0,0 +1,150 @@+import { describe, it, expect } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { db, workspace, team, project, projectColumn, issue, importJob, user } from '@repo/db';+import { eq } from 'drizzle-orm';+import { createLocalIssueAndRecord, type ClaimedImportJob } from '../../import-store';+import { runRewrite } from '../../import-worker';++// Each test makes its own team, project and job, like import-store.test.ts. The job+// row is 'paused' so no other test's claimDueImportJobs picks it up; runRewrite is+// called directly with the job as the worker would have claimed it.++interface LinearJob {+ job: ClaimedImportJob;+ columnId: number;+ projectKey: string;+}++async function makeLinearJob(teamKey: string): Promise<LinearJob> {+ const [ws] = await db+ .insert(workspace)+ .values({ name: 'Importers' })+ .returning({ id: workspace.id });+ const [teamRow] = await db+ .insert(team)+ .values({ workspaceId: ws!.id, name: 'Importers' })+ .returning({ id: team.id });+ const projectKey = randomUUID().slice(0, 8);+ const [projectRow] = await db+ .insert(project)+ .values({ teamId: teamRow!.id, key: projectKey, name: 'Imported' })+ .returning({ id: project.id });+ const [columnRow] = await db+ .insert(projectColumn)+ .values({ projectId: projectRow!.id, name: 'Backlog', position: 1 })+ .returning({ id: projectColumn.id });+ const userId = randomUUID();+ await db.insert(user).values({ id: userId, name: 'Importer', email: `${userId}@example.test` });+ const config = { teamId: 'team-ato', teamKey, projectFilter: 'none', projectId: null };+ const [jobRow] = await db+ .insert(importJob)+ .values({+ projectId: projectRow!.id,+ createdByUserId: userId,+ source: 'linear',+ phase: 'rewrite',+ status: 'paused',+ config,+ })+ .returning({ id: importJob.id });+ return {+ job: {+ id: jobRow!.id,+ projectId: projectRow!.id,+ source: 'linear',+ phase: 'rewrite',+ status: 'paused',+ config,+ cursor: {},+ attempts: 0,+ credentialCiphertext: null,+ credentialIv: null,+ credentialAuthTag: null,+ },+ columnId: columnRow!.id,+ projectKey,+ };+}++async function importIssue(+ { job, columnId }: LinearJob,+ sourceId: string,+ number: number,+ description: string,+): Promise<number> {+ return createLocalIssueAndRecord(job.id, sourceId, String(number), {+ projectId: job.projectId,+ columnId,+ cycleId: null,+ parentId: null,+ assigneeUserId: null,+ title: `Issue ${number}`,+ description,+ priority: null,+ startDate: null,+ dueDate: null,+ });+}++async function issueRow(id: number) {+ const [row] = await db.select().from(issue).where(eq(issue.id, id));+ return row!;+}++describe('runRewrite', () => {+ it("rewrites a mention of another imported issue and keeps the issue's own Linear identifier", async () => {+ const linear = await makeLinearJob('ATO');+ const first = await importIssue(+ linear,+ 'issue-505',+ 505,+ 'Needs ATO-506 first.\n\nImported from Linear: ATO-505',+ );+ const second = await importIssue(linear, 'issue-506', 506, 'Imported from Linear: ATO-506');++ await runRewrite(linear.job);++ const target = await issueRow(second);+ expect((await issueRow(first)).description).toBe(+ `Needs ${linear.projectKey}-${target.sequenceNumber} first.\n\nImported from Linear: ATO-505`,+ );+ expect(target.description).toBe('Imported from Linear: ATO-506');+ });++ it('leaves a mention of an issue that another job imported under the same team key', async () => {+ const other = await makeLinearJob('ATO');+ await importIssue(other, 'issue-12', 12, 'Imported from Linear: ATO-12');+ const linear = await makeLinearJob('ATO');+ const child = await importIssue(+ linear,+ 'issue-505',+ 505,+ 'Parent in Linear: ATO-12\n\nImported from Linear: ATO-505',+ );++ await runRewrite(linear.job);++ expect((await issueRow(child)).description).toBe(+ 'Parent in Linear: ATO-12\n\nImported from Linear: ATO-505',+ );+ });++ it('leaves the footer, a mention outside the job and a URL in the Links section alone', async () => {+ const linear = await makeLinearJob('ATO');+ const description = [+ 'Blocked by ATO-999.',+ '',+ '## Links',+ '',+ '- [Spec](https://linear.app/acme/issue/ATO-506/the-spec)',+ '',+ 'Imported from Linear: ATO-505',+ ].join('\n');+ const first = await importIssue(linear, 'issue-505', 505, description);+ await importIssue(linear, 'issue-506', 506, 'Imported from Linear: ATO-506');++ await runRewrite(linear.job);++ expect((await issueRow(first)).description).toBe(description);+ });+});diff --git a/apps/worker/src/__tests__/integration/import-store.test.ts b/apps/worker/src/__tests__/integration/import-store.test.tsindex 06204758..02c6e066 100644--- a/apps/worker/src/__tests__/integration/import-store.test.ts+++ b/apps/worker/src/__tests__/integration/import-store.test.ts@@ -139,6 +139,35 @@ describe('claimDueImportJobs', () => {});});+describe('import_job source', () => {+ it('accepts a Linear job and claims it with its source', async () => {+ const { projectId, userId } = await makeProject();+ const [row] = await db+ .insert(importJob)+ .values({+ projectId,+ createdByUserId: userId,+ source: 'linear',+ config: { teamId: 'team-1', teamKey: 'ATO', projectFilter: 'none', projectId: null },+ nextAttemptAt: new Date(Date.now() - 1000),+ })+ .returning({ id: importJob.id });++ const job = (await claimDueImportJobs(1000)).find((j) => j.id === row!.id);++ expect(job?.source).toBe('linear');+ });++ it('still refuses a source that has no adapter', async () => {+ const { projectId, userId } = await makeProject();+ const error = await db+ .insert(importJob)+ .values({ projectId, createdByUserId: userId, source: 'jira' })+ .catch((e: unknown) => e);+ expect((error as { cause?: Error }).cause?.message).toContain('import_job_source_check');+ });+});+async function claimJob(jobId: number): Promise<number> {await db.update(importJob)diff --git a/apps/worker/src/__tests__/unit/attachment-download.test.ts b/apps/worker/src/__tests__/unit/attachment-download.test.tsindex 60ee13d3..c87f9d4b 100644--- a/apps/worker/src/__tests__/unit/attachment-download.test.ts+++ b/apps/worker/src/__tests__/unit/attachment-download.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'bun:test';-import type { PinnedRequestInit } from '@repo/net';+import { ResponseTooLargeError, type PinnedRequestInit } from '@repo/net';import {downloadAttachment,AttachmentRejectedError,@@ -45,6 +45,24 @@ describe('downloadAttachment', () => {).rejects.toBeInstanceOf(AttachmentRejectedError);});+ it('rejects a file over the byte limit, which the source did not report a size for', async () => {+ const fetch: AttachmentFetch = async () => {+ throw new ResponseTooLargeError('response exceeds the byte limit');+ };+ const error = await downloadAttachment({ url: FILE_URL }, 1024, fetch).catch((e: unknown) => e);+ expect(error).toBeInstanceOf(AttachmentRejectedError);+ expect((error as Error).message).toContain('1024 bytes');+ });++ it('passes any other download failure through', async () => {+ const fetch: AttachmentFetch = async () => {+ throw new Error('request timed out');+ };+ const error = await downloadAttachment({ url: FILE_URL }, 1024, fetch).catch((e: unknown) => e);+ expect(error).not.toBeInstanceOf(AttachmentRejectedError);+ expect((error as Error).message).toBe('request timed out');+ });+it('downloads with the byte limit and a timeout', async () => {let seen: { url: string; init: PinnedRequestInit | undefined } | null = null;const fetch: AttachmentFetch = async (url, init) => {diff --git a/apps/worker/src/__tests__/unit/cross-reference.test.ts b/apps/worker/src/__tests__/unit/cross-reference.test.tsindex 056be9c7..81983c92 100644--- a/apps/worker/src/__tests__/unit/cross-reference.test.ts+++ b/apps/worker/src/__tests__/unit/cross-reference.test.ts@@ -27,6 +27,14 @@ describe('extractCrossReferences', () => {expect(extractCrossReferences('see rooms-524', 'ROOMS')).toEqual([]);});+ it('does not match an identifier that is a path segment of a URL', () => {+ const text = '[Spec](https://linear.app/acme/issue/ROOMS-524/the-spec)';+ expect(extractCrossReferences(text, 'ROOMS')).toEqual([]);+ expect(applyCrossReferenceReplacements(text, 'ROOMS', new Map([['ROOMS-524', 'X-1']]))).toBe(+ text,+ );+ });+it('finds nothing in text with no mention', () => {expect(extractCrossReferences('no references here', 'ROOMS')).toEqual([]);});diff --git a/apps/worker/src/__tests__/unit/import-retry.test.ts b/apps/worker/src/__tests__/unit/import-retry.test.tsindex c18daec2..7ff01708 100644--- a/apps/worker/src/__tests__/unit/import-retry.test.ts+++ b/apps/worker/src/__tests__/unit/import-retry.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from 'bun:test';import { tickErrorOutcome, MAX_ATTEMPTS } from '../../import-retry';-import { SourceRateLimitedError } from '../../reader';+import { SourceRateLimitedError, UnsupportedImportSourceError } from '../../reader';describe('tickErrorOutcome', () => {it('waits out a rate limit with the exact last_error the Settings page matches', () => {@@ -40,4 +40,11 @@ describe('tickErrorOutcome', () => {it('records a thrown non-Error as its string form', () => {expect(tickErrorOutcome('boom', MAX_ATTEMPTS)).toEqual({ action: 'fail', lastError: 'boom' });});++ it('fails at once for an unsupported source, on the first attempt', () => {+ expect(tickErrorOutcome(new UnsupportedImportSourceError(7, 'jira'), 0)).toEqual({+ action: 'fail',+ lastError: 'import job 7 has unsupported source "jira"',+ });+ });});diff --git a/apps/worker/src/__tests__/unit/import-sources.test.ts b/apps/worker/src/__tests__/unit/import-sources.test.tsindex 4e5541a9..cd7cf425 100644--- a/apps/worker/src/__tests__/unit/import-sources.test.ts+++ b/apps/worker/src/__tests__/unit/import-sources.test.ts@@ -1,6 +1,8 @@import { describe, it, expect } from 'bun:test';import { readerForJob, sourceProjectKeyForJob } from '../../import-sources';+import { LinearReader } from '../../linear-adapter';import { PlaneReader } from '../../plane-adapter';+import { UnsupportedImportSourceError } from '../../reader';const planeCredential = {baseUrl: 'https://plane.example.test',@@ -8,6 +10,8 @@ const planeCredential = {apiKey: 'plane-api-key',};+const linearCredential = { apiKey: 'lin_api_test' };+describe('readerForJob', () => {it('builds a Plane reader for a Plane job', () => {const job = { id: 7, source: 'plane', config: { planeProjectId: 'project-1' } };@@ -21,7 +25,53 @@ describe('readerForJob', () => {);});- it.each(['jira', 'linear', 'toString', ''])('refuses the unsupported source "%s"', (source) => {+ it('builds a Linear reader for one project of a team, or for its issues with no project', () => {+ const forProject = {+ id: 8,+ source: 'linear',+ config: { teamId: 'team-1', teamKey: 'ATO', projectFilter: 'project', projectId: 'p-1' },+ };+ const forNoProject = {+ id: 8,+ source: 'linear',+ config: { teamId: 'team-1', teamKey: 'ATO', projectFilter: 'none', projectId: null },+ };+ expect(readerForJob(forProject, linearCredential)).toBeInstanceOf(LinearReader);+ expect(readerForJob(forNoProject, linearCredential)).toBeInstanceOf(LinearReader);+ });++ it.each([+ { teamKey: 'ATO', projectFilter: 'none', projectId: null },+ { teamId: 'team-1', teamKey: 'ATO', projectFilter: 'project', projectId: null },+ { teamId: 'team-1', teamKey: 'ATO' },+ ])('refuses a Linear job with no complete scope: %o', (config) => {+ const job = { id: 8, source: 'linear', config };+ expect(() => readerForJob(job, linearCredential)).toThrow(+ 'import job 8 has no source project configured',+ );+ });++ it.each([+ ['a Plane-shaped credential', planeCredential],+ ['an empty apiKey', { apiKey: '' }],+ ['a non-string apiKey', { apiKey: 42 }],+ ])('refuses a Linear job whose credential is %s', (_name, credential) => {+ const job = {+ id: 8,+ source: 'linear',+ config: { teamId: 'team-1', teamKey: 'ATO', projectFilter: 'none', projectId: null },+ };+ expect(() => readerForJob(job, credential as never)).toThrow(+ 'import job 8 has a credential that is not a Linear API key',+ );+ });++ it('marks an unsupported source as a permanent error', () => {+ const job = { id: 7, source: 'jira', config: {} };+ expect(() => readerForJob(job, planeCredential)).toThrow(UnsupportedImportSourceError);+ });++ it.each(['jira', 'toString', ''])('refuses the unsupported source "%s"', (source) => {const job = { id: 7, source, config: { planeProjectId: 'project-1' } };expect(() => readerForJob(job, planeCredential)).toThrow(`import job 7 has unsupported source "${source}"`,@@ -43,4 +93,13 @@ describe('sourceProjectKeyForJob', () => {const job = { id: 7, source: 'plane', config: { planeProjectId: 'p' } };expect(sourceProjectKeyForJob(job)).toBeNull();});++ it("returns a Linear job's team key", () => {+ const job = {+ id: 8,+ source: 'linear',+ config: { teamId: 'team-1', teamKey: 'ATO', projectFilter: 'none', projectId: null },+ };+ expect(sourceProjectKeyForJob(job)).toBe('ATO');+ });});diff --git a/apps/worker/src/__tests__/unit/linear-adapter.test.ts b/apps/worker/src/__tests__/unit/linear-adapter.test.tsnew file mode 100644index 00000000..147d3422--- /dev/null+++ b/apps/worker/src/__tests__/unit/linear-adapter.test.ts@@ -0,0 +1,479 @@+import { describe, it, expect } from 'bun:test';+import type { PinnedRequestInit } from '@repo/net';+import { AttachmentRejectedError } from '../../attachment-download';+import {+ LINEAR_GRAPHQL_URL,+ LinearReader,+ linearRateLimitBackoffMs,+ linearUploadHeaders,+ nextUploadHop,+} from '../../linear-adapter';+import type { LinearIssueNode, LinearScope } from '../../linear-mapping';+import { SourceRateLimitedError } from '../../reader';++const API_KEY = 'lin_api_test';+const SCOPE: LinearScope = { teamId: 'team-ato', projectFilter: 'project', projectId: 'proj-tool' };+const UPLOAD = 'https://uploads.linear.app/org-1/file-1/blob-1';+const SIGNED = 'https://storage.example.test/bucket/blob-1?signature=abc';++interface SentRequest {+ url: string;+ init: PinnedRequestInit | undefined;+}++interface GraphqlCall {+ query: string;+ variables: Record<string, unknown>;+}++function readerAnswering(responses: Response[], sent: SentRequest[] = [], scope = SCOPE) {+ const queue = [...responses];+ return new LinearReader({ apiKey: API_KEY }, scope, async (url, init) => {+ sent.push({ url, init });+ const next = queue.shift();+ if (!next) throw new Error(`unexpected request ${url}`);+ return next;+ });+}++function graphqlCall(request: SentRequest): GraphqlCall {+ return JSON.parse(String(request.init?.body)) as GraphqlCall;+}++function page<T>(nodes: T[], endCursor: string | null, hasNextPage: boolean) {+ return { nodes, pageInfo: { hasNextPage, endCursor } };+}++function issueNode(overrides: Partial<LinearIssueNode> = {}): LinearIssueNode {+ return {+ id: 'issue-505',+ identifier: 'ATO-505',+ number: 505,+ title: 'Ship the importer',+ description: `Screenshot `,+ priority: 3,+ dueDate: null,+ createdAt: '2025-01-02T03:04:05.000Z',+ updatedAt: '2025-02-03T04:05:06.000Z',+ state: { id: 'state-todo' },+ assignee: null,+ cycle: null,+ parent: null,+ labels: { nodes: [] },+ attachments: { nodes: [] },+ ...overrides,+ };+}++describe('LinearReader requests', () => {+ it('posts the query with the bare API key to Linear and pages until hasNextPage is false', async () => {+ const sent: SentRequest[] = [];+ const reader = readerAnswering(+ [+ Response.json({+ data: {+ team: {+ connection: page([{ id: 's1', name: 'Todo', type: 'unstarted' }], 'c1', true),+ },+ },+ }),+ Response.json({+ data: {+ team: { connection: page([{ id: 's2', name: 'Triage', type: 'triage' }], 'c2', false) },+ },+ }),+ ],+ sent,+ );++ expect(await reader.listStates()).toEqual([+ { sourceId: 's1', name: 'Todo', category: 'unstarted' },+ { sourceId: 's2', name: 'Triage', category: 'backlog' },+ ]);+ expect(sent.map((r) => r.url)).toEqual([LINEAR_GRAPHQL_URL, LINEAR_GRAPHQL_URL]);+ expect(sent[0]!.init).toMatchObject({+ method: 'POST',+ headers: { Authorization: API_KEY, 'Content-Type': 'application/json' },+ timeoutMs: 15_000,+ });+ expect(sent.map((r) => graphqlCall(r).variables)).toEqual([+ { teamId: 'team-ato', after: null },+ { teamId: 'team-ato', after: 'c1' },+ ]);+ expect(graphqlCall(sent[0]!).query).toContain('includeArchived: true');+ });++ it('lists one project of the team, archived issues included, and returns the next cursor', async () => {+ const sent: SentRequest[] = [];+ const reader = readerAnswering(+ [Response.json({ data: { connection: page([issueNode()], 'cursor-2', true) } })],+ sent,+ );++ const result = await reader.listIssues('cursor-1');++ expect(result.cursor).toBe('cursor-2');+ expect(result.items.map((i) => [i.sourceId, i.sequenceId])).toEqual([['issue-505', 505]]);+ const call = graphqlCall(sent[0]!);+ expect(call.variables).toEqual({+ filter: { team: { id: { eq: 'team-ato' } }, project: { id: { eq: 'proj-tool' } } },+ after: 'cursor-1',+ });+ expect(call.query).toContain('includeArchived: true');+ });++ it("skips issues in Linear's trash, which includeArchived also returns", async () => {+ const sent: SentRequest[] = [];+ const trashed = issueNode({+ id: 'issue-506',+ identifier: 'ATO-506',+ trashed: true,+ labels: { nodes: [], pageInfo: { hasNextPage: true } },+ });+ const reader = readerAnswering(+ [+ Response.json({+ data: { connection: page([issueNode({ trashed: false }), trashed], null, false) },+ }),+ ],+ sent,+ );++ const result = await reader.listIssues(null);++ expect(result.items.map((i) => i.sourceId)).toEqual(['issue-505']);+ expect(graphqlCall(sent[0]!).query).toContain('trashed');+ });++ it("lists the team's issues with no project for a no-project job", async () => {+ const sent: SentRequest[] = [];+ const reader = readerAnswering(+ [Response.json({ data: { connection: page([], null, false) } })],+ sent,+ { teamId: 'team-ato', projectFilter: 'none', projectId: null },+ );++ expect(await reader.listIssues(null)).toEqual({ items: [], cursor: null });+ expect(graphqlCall(sent[0]!).variables).toEqual({+ filter: { team: { id: { eq: 'team-ato' } }, project: { null: true } },+ after: null,+ });+ });++ it('reads the relations an issue owns, never its inverse relations', async () => {+ const sent: SentRequest[] = [];+ const reader = readerAnswering(+ [+ Response.json({+ data: {+ issue: {+ connection: page(+ [+ { type: 'blocks', relatedIssue: { id: 'issue-506' } },+ { type: 'similar', relatedIssue: { id: 'issue-507' } },+ ],+ null,+ false,+ ),+ },+ },+ }),+ ],+ sent,+ );++ expect(await reader.listIssueRelations('issue-505')).toEqual([+ { kind: 'blocks', sourceIssueSourceId: 'issue-505', targetIssueSourceId: 'issue-506' },+ ]);+ const { query } = graphqlCall(sent[0]!);+ expect(query).toContain('relations(');+ expect(query).not.toContain('inverseRelations');+ });++ it('reads an issue and its comments once for the issue, its comments and its uploads', async () => {+ const sent: SentRequest[] = [];+ const reader = readerAnswering(+ [+ Response.json({ data: { issue: issueNode() } }),+ Response.json({+ data: {+ issue: {+ connection: page(+ [+ {+ id: 'comment-1',+ body: '[log.txt](https://uploads.linear.app/org-1/file-2/blob-2)',+ createdAt: '2025-01-05T00:00:00.000Z',+ parent: null,+ user: null,+ botActor: { name: 'GitHub' },+ externalUser: null,+ },+ ],+ null,+ false,+ ),+ },+ },+ }),+ ],+ sent,+ );++ const issue = await reader.getIssue('issue-505');+ const comments = await reader.listIssueComments('issue-505');+ const uploads = await reader.listIssueAttachments('issue-505');++ expect(issue.descriptionMarkdown).toEndWith('Imported from Linear: ATO-505');+ expect(comments).toMatchObject([{ authorEmail: null, authorName: 'GitHub' }]);+ expect(uploads.map((u) => [u.filename, u.contentType])).toEqual([+ ['image.png', 'image/png'],+ ['log.txt', 'text/plain'],+ ]);+ expect(sent).toHaveLength(2);+ expect(graphqlCall(sent[1]!).query).toContain('includeArchived: true');+ });+});++describe('LinearReader errors', () => {+ it('throws the source-neutral rate-limit error on RATELIMITED', async () => {+ const reset = Date.now() + 30_000;+ const reader = readerAnswering([+ Response.json(+ { errors: [{ message: 'Rate limit exceeded', extensions: { code: 'RATELIMITED' } }] },+ {+ status: 400,+ headers: {+ 'x-ratelimit-requests-remaining': '0',+ 'x-ratelimit-requests-reset': String(reset),+ },+ },+ ),+ ]);++ const error = await reader.listStates().catch((e: unknown) => e);++ expect(error).toBeInstanceOf(SourceRateLimitedError);+ expect((error as Error).message).toBe('Linear rate limit reached');+ expect((error as SourceRateLimitedError).retryAfterMs).toBeGreaterThan(25_000);+ expect((error as SourceRateLimitedError).retryAfterMs).toBeLessThanOrEqual(30_000);+ });++ it('fails the tick with the GraphQL error message, a rejected key included', async () => {+ const reader = readerAnswering([+ Response.json(+ {+ errors: [+ {+ message: 'Authentication required, not authenticated',+ extensions: { code: 'AUTHENTICATION_ERROR' },+ },+ ],+ },+ { status: 401 },+ ),+ ]);+ await expect(reader.listStates()).rejects.toThrow(+ 'Linear request failed: Authentication required, not authenticated',+ );+ });++ it('fails the tick on an HTTP error with no GraphQL body', async () => {+ const reader = readerAnswering([new Response('<html>bad gateway</html>', { status: 502 })]);+ await expect(reader.listStates()).rejects.toThrow('Linear request failed: HTTP 502');+ });+});++describe('linearRateLimitBackoffMs', () => {+ const now = 1_000_000;++ it('is null for a request that was not rate limited', () => {+ expect(+ linearRateLimitBackoffMs({ status: 200, errorCodes: [], headers: new Headers() }, now),+ ).toBeNull();+ });++ it('waits a minute when no used-up budget says when it resets', () => {+ expect(+ linearRateLimitBackoffMs(+ { status: 400, errorCodes: ['RATELIMITED'], headers: new Headers() },+ now,+ ),+ ).toBe(60_000);+ expect(+ linearRateLimitBackoffMs({ status: 429, errorCodes: [], headers: new Headers() }, now),+ ).toBe(60_000);+ });++ it('waits until the latest reset of a used-up budget, at least a second', () => {+ const headers = new Headers({+ 'x-ratelimit-requests-remaining': '0',+ 'x-ratelimit-requests-reset': String(now + 20_000),+ 'x-ratelimit-complexity-remaining': '0',+ 'x-ratelimit-complexity-reset': String(now + 45_000),+ 'x-ratelimit-endpoint-requests-remaining': '7',+ 'x-ratelimit-endpoint-requests-reset': String(now + 900_000),+ });+ expect(+ linearRateLimitBackoffMs({ status: 400, errorCodes: ['RATELIMITED'], headers }, now),+ ).toBe(45_000);+ const past = new Headers({+ 'x-ratelimit-requests-remaining': '0',+ 'x-ratelimit-requests-reset': String(now - 5000),+ });+ expect(+ linearRateLimitBackoffMs({ status: 400, errorCodes: ['RATELIMITED'], headers: past }, now),+ ).toBe(1000);+ });++ it("waits at most an hour, Linear's own window, whatever the reset header says", () => {+ const headers = new Headers({+ 'x-ratelimit-requests-remaining': '0',+ 'x-ratelimit-requests-reset': String(now + 30 * 24 * 3_600_000),+ });+ expect(+ linearRateLimitBackoffMs({ status: 400, errorCodes: ['RATELIMITED'], headers }, now),+ ).toBe(3_600_000);+ });+});++describe('resolveAttachmentDownload', () => {+ const sourceId = `issue-505 ${UPLOAD}`;++ it('downloads a file Linear serves itself with the API key, reading only the head', async () => {+ const sent: SentRequest[] = [];+ const reader = readerAnswering([new Response('', { status: 200 })], sent);++ expect(await reader.resolveAttachmentDownload('issue-505', sourceId)).toStrictEqual({+ url: UPLOAD,+ headers: { Authorization: API_KEY },+ });+ expect(sent).toEqual([+ {+ url: UPLOAD,+ init: {+ headers: { Authorization: API_KEY },+ timeoutMs: 15_000,+ maxBytes: 0,+ truncateBody: true,+ },+ },+ ]);+ });++ it('follows a redirect chain itself and never sends the key past uploads.linear.app', async () => {+ const sent: SentRequest[] = [];+ const reader = readerAnswering(+ [+ new Response(null, { status: 307, headers: { location: '/org-1/file-1/blob-1-v2' } }),+ new Response(null, { status: 302, headers: { location: SIGNED } }),+ new Response('', { status: 200 }),+ ],+ sent,+ );++ expect(await reader.resolveAttachmentDownload('issue-505', sourceId)).toStrictEqual({+ url: SIGNED,+ });+ expect(sent.map((r) => [r.url, r.init?.headers])).toEqual([+ [UPLOAD, { Authorization: API_KEY }],+ ['https://uploads.linear.app/org-1/file-1/blob-1-v2', { Authorization: API_KEY }],+ [SIGNED, undefined],+ ]);+ });++ it.each([401, 403, 404, 500])('skips a file the host answers with HTTP %d', async (status) => {+ const reader = readerAnswering([new Response('nope', { status })]);+ const error = await reader+ .resolveAttachmentDownload('issue-505', sourceId)+ .catch((e: unknown) => e);+ expect(error).toBeInstanceOf(AttachmentRejectedError);+ expect((error as Error).message).toBe(`Linear file storage answered HTTP ${status}`);+ });++ it('waits out a 429 from the file host instead of skipping the file', async () => {+ const reader = readerAnswering([new Response('', { status: 429 })]);+ await expect(reader.resolveAttachmentDownload('issue-505', sourceId)).rejects.toBeInstanceOf(+ SourceRateLimitedError,+ );+ });++ it('skips a file that redirects to plain http or keeps redirecting', async () => {+ const insecure = readerAnswering([+ new Response(null, { status: 302, headers: { location: 'http://storage.example.test/x' } }),+ ]);+ await expect(insecure.resolveAttachmentDownload('issue-505', sourceId)).rejects.toThrow(+ 'Linear file storage redirected to a non-https URL',+ );++ const loop = readerAnswering(+ Array.from(+ { length: 4 },+ () => new Response(null, { status: 302, headers: { location: UPLOAD } }),+ ),+ );+ await expect(loop.resolveAttachmentDownload('issue-505', sourceId)).rejects.toThrow(+ 'Linear file storage redirected more than 3 times',+ );+ });+});++describe('upload helpers', () => {+ it('sends the API key only to uploads.linear.app', () => {+ expect(linearUploadHeaders(UPLOAD, API_KEY)).toEqual({ Authorization: API_KEY });+ expect(linearUploadHeaders(SIGNED, API_KEY)).toBeUndefined();+ expect(linearUploadHeaders('https://uploads.linear.app.evil.test/x', API_KEY)).toBeUndefined();+ });++ it('reads a redirect without a location as a refusal', () => {+ expect(() => nextUploadHop(UPLOAD, 302, null)).toThrow(+ 'Linear file storage redirected nowhere',+ );+ expect(nextUploadHop(UPLOAD, 204, null)).toEqual({ kind: 'download' });+ expect(nextUploadHop(UPLOAD, 410, null)).toEqual({ kind: 'refused' });+ });+});++describe('LinearReader completeness and scope', () => {+ it.each(['labels', 'attachments'] as const)(+ 'fails loudly when an issue has more %s than one page',+ async (name) => {+ const node = issueNode({+ [name]: { nodes: [], pageInfo: { hasNextPage: true } },+ } as Partial<LinearIssueNode>);+ const message = `Linear issue ATO-505 has more than 50 ${name}; stopping to avoid a truncated import`;+ await expect(+ readerAnswering([+ Response.json({ data: { connection: page([node], null, false) } }),+ ]).listIssues(null),+ ).rejects.toThrow(message);+ await expect(+ readerAnswering([Response.json({ data: { issue: node } })]).getIssue('issue-505'),+ ).rejects.toThrow(message);+ },+ );++ it('asks for archived link attachments and the nested page info', async () => {+ const sent: SentRequest[] = [];+ await readerAnswering(+ [Response.json({ data: { connection: page([], null, false) } })],+ sent,+ ).listIssues(null);+ const { query } = graphqlCall(sent[0]!);+ expect(query).toContain('attachments(first: 50, includeArchived: true)');+ expect(query.match(/pageInfo \{ hasNextPage \}/g)).toHaveLength(2);+ });++ it('refuses a project scope without a project id', () => {+ for (const projectId of [null, '']) {+ expect(+ () =>+ new LinearReader(+ { apiKey: API_KEY },+ { ...SCOPE, projectId },+ async () => new Response(),+ ),+ ).toThrow('Linear scope needs a projectId');+ }+ });+});diff --git a/apps/worker/src/__tests__/unit/linear-mapping.test.ts b/apps/worker/src/__tests__/unit/linear-mapping.test.tsnew file mode 100644index 00000000..01c3551e--- /dev/null+++ b/apps/worker/src/__tests__/unit/linear-mapping.test.ts@@ -0,0 +1,471 @@+import { describe, it, expect } from 'bun:test';+import {+ extractLinearUploads,+ linearCommentAuthor,+ linearIssueLinksToIdentifiers,+ linearNextCursor,+ linearPriority,+ linearStateCategory,+ linearUploadSourceId,+ linearUploadUrl,+ mapLinearComments,+ mapLinearCycles,+ mapLinearIssue,+ mapLinearLabels,+ mapLinearRelations,+ type LinearCommentNode,+ type LinearIssueNode,+ type LinearScope,+} from '../../linear-mapping';++const TEAM = 'team-ato';+const PROJECT_SCOPE: LinearScope = {+ teamId: TEAM,+ projectFilter: 'project',+ projectId: 'proj-tool',+};+const NO_PROJECT_SCOPE: LinearScope = { teamId: TEAM, projectFilter: 'none', projectId: null };+const UPLOAD = 'https://uploads.linear.app/org-1/file-1/blob-1';++function issueNode(overrides: Partial<LinearIssueNode> = {}): LinearIssueNode {+ return {+ id: 'issue-505',+ identifier: 'ATO-505',+ number: 505,+ title: 'Ship the importer',+ description: 'Body text.',+ priority: 2,+ dueDate: '2026-11-01',+ createdAt: '2025-01-02T03:04:05.000Z',+ updatedAt: '2025-02-03T04:05:06.000Z',+ state: { id: 'state-todo' },+ assignee: { email: '[email protected]' },+ cycle: { id: 'cycle-7' },+ parent: null,+ labels: { nodes: [{ id: 'label-bug' }, { id: 'label-api' }] },+ attachments: { nodes: [] },+ ...overrides,+ };+}++function commentNode(overrides: Partial<LinearCommentNode> = {}): LinearCommentNode {+ return {+ id: 'comment-1',+ body: 'Looks good.',+ createdAt: '2025-01-05T00:00:00.000Z',+ parent: null,+ user: { email: '[email protected]', name: 'Thomas' },+ botActor: null,+ externalUser: null,+ ...overrides,+ };+}++describe('linearStateCategory', () => {+ it.each([+ ['triage', 'backlog'],+ ['backlog', 'backlog'],+ ['unstarted', 'unstarted'],+ ['started', 'started'],+ ['completed', 'completed'],+ ['canceled', 'canceled'],+ ['duplicate', 'canceled'],+ ['something-new', 'backlog'],+ ])('maps the state type %s to %s', (type, category) => {+ expect(linearStateCategory(type)).toBe(category as ReturnType<typeof linearStateCategory>);+ });+});++describe('linearPriority', () => {+ it.each([+ [0, null],+ [1, 'urgent'],+ [2, 'high'],+ [3, 'medium'],+ [4, 'low'],+ [9, null],+ ])('maps priority %d to %p', (priority, value) => {+ expect(linearPriority(priority)).toBe(value);+ });+});++describe('mapLinearLabels', () => {+ it('names a grouped label Group/Name, keeps its color, and drops the group itself', () => {+ expect(+ mapLinearLabels([+ { id: 'g', name: 'kind', color: '#111111', isGroup: true, parent: null },+ { id: 'l1', name: 'bug', color: '#ff0000', isGroup: false, parent: { name: 'kind' } },+ { id: 'l2', name: 'Feature', color: '#00ff00', isGroup: false, parent: null },+ ]),+ ).toEqual([+ { sourceId: 'l1', name: 'kind/bug', color: '#ff0000' },+ { sourceId: 'l2', name: 'Feature', color: '#00ff00' },+ ]);+ });+});++describe('mapLinearCycles', () => {+ it('keeps the dates only and names an unnamed cycle by its number', () => {+ expect(+ mapLinearCycles([+ {+ id: 'c1',+ number: 3,+ name: null,+ startsAt: '2026-01-05T08:00:00.000Z',+ endsAt: '2026-01-19T08:00:00.000Z',+ description: null,+ },+ {+ id: 'c2',+ number: 4,+ name: 'Launch',+ startsAt: '2026-01-19T08:00:00.000Z',+ endsAt: '2026-02-02T08:00:00.000Z',+ description: 'Ship it',+ },+ ]),+ ).toEqual([+ {+ sourceId: 'c1',+ name: 'Cycle 3',+ startDate: '2026-01-05',+ endDate: '2026-01-19',+ goal: undefined,+ },+ {+ sourceId: 'c2',+ name: 'Launch',+ startDate: '2026-01-19',+ endDate: '2026-02-02',+ goal: 'Ship it',+ },+ ]);+ });+});++describe('linearIssueLinksToIdentifiers', () => {+ const url = 'https://linear.app/atomlab77/issue/ATO-589/egress-step-2-the-vyos-gateway';++ it('turns a bare Linear issue URL into its identifier', () => {+ expect(linearIssueLinksToIdentifiers(`Follow-up of ${url}.`)).toBe('Follow-up of ATO-589.');+ });++ it('turns an autolink into its identifier', () => {+ expect(linearIssueLinksToIdentifiers(`See <${url}>`)).toBe('See ATO-589');+ });++ it('keeps a link label that already names the issue, and appends the identifier otherwise', () => {+ expect(linearIssueLinksToIdentifiers(`[ATO-589](${url})`)).toBe('ATO-589');+ expect(linearIssueLinksToIdentifiers(`[ATO-589 the gateway](${url})`)).toBe(+ 'ATO-589 the gateway',+ );+ expect(linearIssueLinksToIdentifiers(`[the gateway](${url}?comment=1)`)).toBe(+ 'the gateway (ATO-589)',+ );+ expect(linearIssueLinksToIdentifiers(`[${url}](${url})`)).toBe('ATO-589');+ });++ it('leaves other links, uploads and plain identifiers alone', () => {+ const text = `ATO-1, https://linear.app/atomlab77/project/the-tool-123 and `;+ expect(linearIssueLinksToIdentifiers(text)).toBe(text);+ });+});++describe('mapLinearIssue', () => {+ it('maps every field the import keeps', () => {+ expect(mapLinearIssue(issueNode(), PROJECT_SCOPE)).toEqual({+ sourceId: 'issue-505',+ sequenceId: 505,+ title: 'Ship the importer',+ descriptionMarkdown: 'Body text.\n\nImported from Linear: ATO-505',+ stateSourceId: 'state-todo',+ assigneeEmail: '[email protected]',+ labelSourceIds: ['label-bug', 'label-api'],+ cycleSourceId: 'cycle-7',+ parentSourceId: null,+ priority: 'high',+ startDate: null,+ dueDate: '2026-11-01',+ customFields: [],+ createdAt: '2025-01-02T03:04:05.000Z',+ updatedAt: '2025-02-03T04:05:06.000Z',+ });+ });++ it('imports an issue with no assignee, no cycle, no priority and no description', () => {+ const issue = mapLinearIssue(+ issueNode({ assignee: null, cycle: null, priority: 0, description: null }),+ PROJECT_SCOPE,+ );+ expect(issue).toMatchObject({+ assigneeEmail: null,+ cycleSourceId: null,+ priority: null,+ descriptionMarkdown: 'Imported from Linear: ATO-505',+ });+ });++ it('lists link attachments under Links and leaves uploaded files out of it', () => {+ const issue = mapLinearIssue(+ issueNode({+ attachments: {+ nodes: [+ { title: 'Fix [api] #12', url: 'https://github.com/acme/app/pull/12' },+ { title: 'diagram.png', url: UPLOAD },+ { title: '', url: 'https://example.com/spec' },+ { title: 'C:\\temp\\', url: 'https://example.com/dir' },+ ],+ },+ }),+ PROJECT_SCOPE,+ );+ expect(issue.descriptionMarkdown).toBe(+ [+ 'Body text.',+ '## Links\n\n- [Fix \\[api\\] #12](https://github.com/acme/app/pull/12)\n- [https://example.com/spec](https://example.com/spec)\n- [C:\\\\temp\\\\](https://example.com/dir)',+ 'Imported from Linear: ATO-505',+ ].join('\n\n'),+ );+ });++ it('names a parent outside this job, and keeps the parent id either way', () => {+ const outside = mapLinearIssue(+ issueNode({+ parent: {+ id: 'issue-12',+ identifier: 'ATO-12',+ team: { id: TEAM },+ project: { id: 'proj-other' },+ },+ }),+ PROJECT_SCOPE,+ );+ expect(outside.parentSourceId).toBe('issue-12');+ expect(outside.descriptionMarkdown).toBe(+ 'Body text.\n\nParent in Linear: ATO-12\n\nImported from Linear: ATO-505',+ );++ const inside = mapLinearIssue(+ issueNode({+ parent: { id: 'issue-13', identifier: 'ATO-13', team: { id: TEAM }, project: null },+ }),+ NO_PROJECT_SCOPE,+ );+ expect(inside.parentSourceId).toBe('issue-13');+ expect(inside.descriptionMarkdown).toBe('Body text.\n\nImported from Linear: ATO-505');+ });++ it('rewrites Linear issue links in the description to bare identifiers', () => {+ const issue = mapLinearIssue(+ issueNode({ description: 'Blocked on https://linear.app/atomlab77/issue/ATO-506/db' }),+ PROJECT_SCOPE,+ );+ expect(issue.descriptionMarkdown).toBe('Blocked on ATO-506\n\nImported from Linear: ATO-505');+ });+});++describe('mapLinearComments', () => {+ it('orders comments oldest first and keeps reply threading and dates', () => {+ const comments = mapLinearComments([+ commentNode({ id: 'reply', createdAt: '2025-01-06T00:00:00.000Z', parent: { id: 'root' } }),+ commentNode({ id: 'root', createdAt: '2025-01-05T00:00:00.000Z' }),+ ]);+ expect(comments.map((c) => [c.sourceId, c.replyToSourceId, c.createdAt])).toEqual([+ ['root', null, '2025-01-05T00:00:00.000Z'],+ ['reply', 'root', '2025-01-06T00:00:00.000Z'],+ ]);+ });++ it('rewrites Linear issue links in a comment body', () => {+ const [comment] = mapLinearComments([+ commentNode({ body: 'Dup of https://linear.app/atomlab77/issue/ATO-7/x' }),+ ]);+ expect(comment!.bodyMarkdown).toBe('Dup of ATO-7');+ });+});++describe('linearCommentAuthor', () => {+ it('uses the user email and name', () => {+ expect(linearCommentAuthor(commentNode())).toEqual({+ authorEmail: '[email protected]',+ authorName: 'Thomas',+ });+ });++ it('keeps a bot comment with no email under the bot name', () => {+ expect(linearCommentAuthor(commentNode({ user: null, botActor: { name: 'GitHub' } }))).toEqual({+ authorEmail: null,+ authorName: 'GitHub',+ });+ });++ it('falls back to the external author, then to Linear', () => {+ expect(+ linearCommentAuthor(commentNode({ user: null, externalUser: { name: 'Jay (Slack)' } })),+ ).toEqual({ authorEmail: null, authorName: 'Jay (Slack)' });+ expect(linearCommentAuthor(commentNode({ user: null, botActor: { name: null } }))).toEqual({+ authorEmail: null,+ authorName: 'Linear',+ });+ });+});++describe('mapLinearRelations', () => {+ it('maps the relations this issue owns, keeps their direction, and drops similar', () => {+ expect(+ mapLinearRelations('issue-505', [+ { type: 'blocks', relatedIssue: { id: 'issue-506' } },+ { type: 'duplicate', relatedIssue: { id: 'issue-400' } },+ { type: 'related', relatedIssue: { id: 'issue-12' } },+ { type: 'similar', relatedIssue: { id: 'issue-13' } },+ { type: 'something-new', relatedIssue: { id: 'issue-14' } },+ ]),+ ).toEqual([+ { kind: 'blocks', sourceIssueSourceId: 'issue-505', targetIssueSourceId: 'issue-506' },+ { kind: 'duplicates', sourceIssueSourceId: 'issue-505', targetIssueSourceId: 'issue-400' },+ { kind: 'relates', sourceIssueSourceId: 'issue-505', targetIssueSourceId: 'issue-12' },+ ]);+ });+});++describe('linearNextCursor', () => {+ it('stops on hasNextPage false even when an end cursor is present', () => {+ expect(linearNextCursor({ hasNextPage: false, endCursor: 'abc' })).toBeNull();+ expect(linearNextCursor({ hasNextPage: true, endCursor: 'abc' })).toBe('abc');+ });+});++describe('extractLinearUploads', () => {+ it('finds uploads in images, file links and bare URLs, first mention wins', () => {+ const uploads = extractLinearUploads(+ 'issue-505',+ [+ `Before  and [report.pdf](https://uploads.linear.app/org-1/file-2/blob-2)`,+ null,+ `Again ${UPLOAD} and https://uploads.linear.app/org-1/file-3/blob-3`,+ ],+ [{ title: 'spec.docx', url: 'https://uploads.linear.app/org-1/file-4/blob-4' }],+ );+ expect(uploads).toEqual([+ {+ sourceId: `issue-505 ${UPLOAD}`,+ filename: 'image.png',+ contentType: 'image/png',+ sizeBytes: 0,+ },+ {+ sourceId: 'issue-505 https://uploads.linear.app/org-1/file-2/blob-2',+ filename: 'report.pdf',+ contentType: 'application/pdf',+ sizeBytes: 0,+ },+ {+ sourceId: 'issue-505 https://uploads.linear.app/org-1/file-3/blob-3',+ filename: 'blob-3',+ contentType: 'application/octet-stream',+ sizeBytes: 0,+ },+ {+ sourceId: 'issue-505 https://uploads.linear.app/org-1/file-4/blob-4',+ filename: 'spec.docx',+ contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ sizeBytes: 0,+ },+ ]);+ });++ it('gives each of several files with the same name its own name', () => {+ const uploads = extractLinearUploads(+ 'issue-505',+ [+ ' ',+ ' [notes](https://uploads.linear.app/o/a/4) [notes](https://uploads.linear.app/o/a/5)',+ ],+ [],+ );+ expect(uploads.map((u) => u.filename)).toEqual([+ 'image.png',+ 'image (2).png',+ 'Image (3).png',+ 'notes',+ 'notes (2)',+ ]);+ });++ it('ignores links to anything but uploads.linear.app', () => {+ expect(+ extractLinearUploads(+ 'issue-505',+ [''],+ [{ title: 'PR', url: 'https://github.com/acme/app/pull/1' }],+ ),+ ).toEqual([]);+ });+});++describe('linearUploadUrl', () => {+ it('recovers the upload URL from its source id', () => {+ expect(linearUploadUrl('issue-505', linearUploadSourceId('issue-505', UPLOAD))).toBe(UPLOAD);+ });++ it('refuses a source id of another issue or another host', () => {+ expect(() => linearUploadUrl('issue-506', `issue-505 ${UPLOAD}`)).toThrow(+ 'is not a Linear upload of issue issue-506',+ );+ expect(() => linearUploadUrl('issue-505', 'issue-505 https://evil.example/x')).toThrow(+ 'is not a Linear upload of issue issue-505',+ );+ });+});++describe('fix round 1', () => {+ it('strips sentence punctuation from a bare upload URL but not from a link destination', () => {+ const uploads = extractLinearUploads(+ 'issue-505',+ [+ 'see https://uploads.linear.app/o/f/b. And (https://uploads.linear.app/o/f/c), then https://uploads.linear.app/o/f/d?!',+ '[x](https://uploads.linear.app/o/f/e.)',+ ],+ [],+ );+ expect(uploads.map((u) => u.sourceId)).toEqual([+ 'issue-505 https://uploads.linear.app/o/f/b',+ 'issue-505 https://uploads.linear.app/o/f/c',+ 'issue-505 https://uploads.linear.app/o/f/d',+ 'issue-505 https://uploads.linear.app/o/f/e.',+ ]);+ });++ it('never generates a filename that another file already has', () => {+ const uploads = extractLinearUploads(+ 'issue-505',+ [+ '  ',+ ],+ [],+ );+ const names = uploads.map((u) => u.filename);+ expect(new Set(names.map((n) => n.toLowerCase())).size).toBe(3);+ expect(names[0]).toBe('image.png');+ });++ it('gives cycles with a repeated name distinct names', () => {+ const base = { startsAt: '2026-01-05T08:00:00.000Z', endsAt: '2026-01-19T08:00:00.000Z' };+ const names = mapLinearCycles([+ { id: 'a', number: 1, name: 'Sprint', description: null, ...base },+ { id: 'b', number: 2, name: 'sprint', description: null, ...base },+ { id: 'c', number: 3, name: null, description: null, ...base },+ { id: 'd', number: 4, name: 'Cycle 3', description: null, ...base },+ ]).map((c) => c.name);+ expect(names[0]).toBe('Sprint');+ expect(names[1]).toBe('sprint (Cycle 2)');+ expect(names[2]).toBe('Cycle 3');+ expect(names[3]).toBe('Cycle 3 (Cycle 4)');+ });++ it('refuses a next page that has no cursor', () => {+ expect(() => linearNextCursor({ hasNextPage: true, endCursor: null })).toThrow('no end cursor');+ expect(linearNextCursor({ hasNextPage: false, endCursor: null })).toBeNull();+ });+});diff --git a/apps/worker/src/attachment-download.ts b/apps/worker/src/attachment-download.tsindex 2f81f95e..9f3a471e 100644--- a/apps/worker/src/attachment-download.ts+++ b/apps/worker/src/attachment-download.ts@@ -1,4 +1,4 @@-import { pinnedFetch } from '@repo/net';+import { pinnedFetch, ResponseTooLargeError } from '@repo/net';import type { AttachmentDownload } from './reader';// An attachment that cannot be stored: over this instance's size, type or quota@@ -10,6 +10,26 @@ export type AttachmentFetch = typeof pinnedFetch;const DOWNLOAD_TIMEOUT_MS = 30_000;+// A source that reports no size (Linear) is only caught by the byte limit itself.+async function fetchWithinLimit(+ download: AttachmentDownload,+ maxBytes: number,+ fetch: AttachmentFetch,+): Promise<Response> {+ try {+ return await fetch(download.url, {+ headers: download.headers,+ timeoutMs: DOWNLOAD_TIMEOUT_MS,+ maxBytes,+ });+ } catch (error) {+ if (error instanceof ResponseTooLargeError) {+ throw new AttachmentRejectedError(`the file is larger than ${maxBytes} bytes`);+ }+ throw error;+ }+}+// pinnedFetch returns any status as-is, a redirect included, so an error page// must be refused here or it would be stored as the file.export async function downloadAttachment(@@ -17,11 +37,7 @@ export async function downloadAttachment(maxBytes: number,fetch: AttachmentFetch = pinnedFetch,): Promise<Buffer> {- const res = await fetch(download.url, {- headers: download.headers,- timeoutMs: DOWNLOAD_TIMEOUT_MS,- maxBytes,- });+ const res = await fetchWithinLimit(download, maxBytes, fetch);if (!res.ok) {throw new AttachmentRejectedError(`the download answered HTTP ${res.status}`);}diff --git a/apps/worker/src/cross-reference.ts b/apps/worker/src/cross-reference.tsindex e5e3e6ac..ac5b20e5 100644--- a/apps/worker/src/cross-reference.ts+++ b/apps/worker/src/cross-reference.ts@@ -8,8 +8,10 @@ function escapeRegExp(value: string): string {return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');}+// (?<!/) leaves an identifier that is a segment of a URL path alone, so a link's+// address is never rewritten.function crossReferencePattern(sourceProjectKey: string): RegExp {- return new RegExp(`\\b${escapeRegExp(sourceProjectKey)}-(\\d+)\\b`, 'g');+ return new RegExp(`(?<!/)\\b${escapeRegExp(sourceProjectKey)}-(\\d+)\\b`, 'g');}export interface CrossReferenceMatch {diff --git a/apps/worker/src/import-retry.ts b/apps/worker/src/import-retry.tsindex bf8bbdd7..27982bee 100644--- a/apps/worker/src/import-retry.ts+++ b/apps/worker/src/import-retry.ts@@ -1,5 +1,5 @@import { equalJitterBackoffMs } from './backoff';-import { SourceRateLimitedError } from './reader';+import { SourceRateLimitedError, UnsupportedImportSourceError } from './reader';// import-store.ts resets job.attempts to 0 on every tick that makes progress, so// this counts consecutive failed ticks: a long import does not fail itself out.@@ -21,6 +21,10 @@ export function tickErrorOutcome(error: unknown, attempts: number): TickErrorOutcountsAsAttempt: false,};}+ // No retry can give a job a source this worker does not have.+ if (error instanceof UnsupportedImportSourceError) {+ return { action: 'fail', lastError: error.message };+ }const message = error instanceof Error ? error.message : String(error);if (attempts >= MAX_ATTEMPTS) return { action: 'fail', lastError: message };return {diff --git a/apps/worker/src/import-sources.ts b/apps/worker/src/import-sources.tsindex 9f94147a..07156928 100644--- a/apps/worker/src/import-sources.ts+++ b/apps/worker/src/import-sources.ts@@ -1,6 +1,7 @@import type { CanonicalStateCategory } from './canonical';+import { LinearReader, type LinearCredential } from './linear-adapter';import { PlaneReader, type PlaneCredential } from './plane-adapter';-import type { SourceReader } from './reader';+import { UnsupportedImportSourceError, type SourceReader } from './reader';// The import_job.config fields every source shares; the phases read them directly.export interface CommonImportConfig {@@ -14,14 +15,25 @@ export interface PlaneImportConfig extends CommonImportConfig {planeProjectKey?: string;}+export interface LinearImportConfig extends CommonImportConfig {+ teamId: string;+ // The team's issue-key prefix ("ATO" in "ATO-505") for Rewrite.+ teamKey: string;+ // One job imports one project of the team, or the team's issues with no project.+ projectFilter: 'project' | 'none';+ projectId: string | null;+}+// One entry per import_job.source. A new source adds a member to both maps and an// entry to IMPORT_SOURCES.export interface ImportCredentials {plane: PlaneCredential;+ linear: LinearCredential;}export interface ImportConfigs {plane: PlaneImportConfig;+ linear: LinearImportConfig;}export type ImportSourceKind = keyof ImportConfigs;@@ -48,6 +60,26 @@ const IMPORT_SOURCES: { [S in ImportSourceKind]: ImportSourceDefinition<S> } = {},projectKey: (config) => config.planeProjectKey ?? null,},+ linear: {+ buildReader(credential, config, jobId) {+ // The registry types do not tie a decrypted credential to its job's source.+ // Exactly { apiKey }: a Plane credential also has an apiKey, plus baseUrl and workspaceSlug.+ const keys = credential && typeof credential === 'object' ? Object.keys(credential) : [];+ if (keys.length !== 1 || typeof credential.apiKey !== 'string' || credential.apiKey === '') {+ throw new Error(`import job ${jobId} has a credential that is not a Linear API key`);+ }+ const { teamId, projectFilter, projectId } = config;+ if (!teamId || !(projectFilter === 'none' || (projectFilter === 'project' && projectId))) {+ throw new Error(`import job ${jobId} has no source project configured`);+ }+ return new LinearReader(credential, {+ teamId,+ projectFilter,+ projectId: projectFilter === 'project' ? (projectId ?? null) : null,+ });+ },+ projectKey: (config) => config.teamKey ?? null,+ },};export interface ImportJobSource {@@ -58,7 +90,7 @@ export interface ImportJobSource {function sourceOf(job: ImportJobSource): ImportSourceKind {if (!Object.hasOwn(IMPORT_SOURCES, job.source)) {- throw new Error(`import job ${job.id} has unsupported source "${job.source}"`);+ throw new UnsupportedImportSourceError(job.id, job.source);}return job.source as ImportSourceKind;}diff --git a/apps/worker/src/import-worker.ts b/apps/worker/src/import-worker.tsindex ed457779..d8f78d27 100644--- a/apps/worker/src/import-worker.ts+++ b/apps/worker/src/import-worker.ts@@ -362,10 +362,13 @@ async function runLink(job: ClaimedImportJob, reader: SourceReader): Promise<voi// project's own identifier. Purely local: everything it needs was captured// during Create/Link, so it makes no further Plane requests.+// A mention of the issue whose own text this is stays as written: it is how a+// source records the issue's own identifier ("Imported from Linear: ATO-505").async function rewriteCrossReferences(jobId: number,sourceProjectKey: string,localProjectKey: string,+ issueLocalId: number,text: string,): Promise<string> {const references = extractCrossReferences(text, sourceProjectKey);@@ -374,7 +377,7 @@ async function rewriteCrossReferences(const replacements = new Map<string, string>();for (const { reference, sequenceId } of references) {const record = await findImportRecordByDisplayId(jobId, 'issue', sequenceId);- if (record?.localId == null) continue;+ if (record?.localId == null || record.localId === issueLocalId) continue;const targetSequence = await getIssueSequenceNumber(record.localId);if (targetSequence == null) continue;replacements.set(reference, `${localProjectKey}-${targetSequence}`);@@ -382,7 +385,7 @@ async function rewriteCrossReferences(return applyCrossReferenceReplacements(text, sourceProjectKey, replacements);}-async function runRewrite(job: ClaimedImportJob): Promise<void> {+export async function runRewrite(job: ClaimedImportJob): Promise<void> {const cursor = job.cursor as Partial<RecordCursor>;const afterId = cursor.lastRecordId ?? 0;const pending = await listCreatedImportRecords(job.id, 'issue', afterId, ISSUES_PER_TICK);@@ -402,6 +405,7 @@ async function runRewrite(job: ClaimedImportJob): Promise<void> {job.id,sourceProjectKey,localProjectKey,+ record.localId,description,);if (nextDescription !== description) {@@ -412,6 +416,7 @@ async function runRewrite(job: ClaimedImportJob): Promise<void> {job.id,sourceProjectKey,localProjectKey,+ record.localId,comment.body,);if (nextBody !== comment.body) await updateCommentBody(comment.id, nextBody);diff --git a/apps/worker/src/linear-adapter.ts b/apps/worker/src/linear-adapter.tsnew file mode 100644index 00000000..7a39ae1f--- /dev/null+++ b/apps/worker/src/linear-adapter.ts@@ -0,0 +1,382 @@+import { pinnedFetch } from '@repo/net';+import { AttachmentRejectedError } from './attachment-download';+import {+ SourceRateLimitedError,+ type AttachmentDownload,+ type Page,+ type SourceReader,+} from './reader';+import type {+ CanonicalAttachment,+ CanonicalComment,+ CanonicalCycle,+ CanonicalIssue,+ CanonicalLabel,+ CanonicalRelation,+ CanonicalState,+} from './canonical';+import {+ extractLinearUploads,+ linearNextCursor,+ linearUploadUrl,+ mapLinearComments,+ mapLinearCycles,+ mapLinearIssue,+ mapLinearLabels,+ mapLinearRelations,+ mapLinearStates,+ type LinearCommentNode,+ type LinearConnection,+ type LinearCycleNode,+ type LinearIssueNode,+ type LinearLabelNode,+ type LinearRelationNode,+ type LinearScope,+ type LinearStateNode,+} from './linear-mapping';++// The SourceReader for Linear: its GraphQL API with a personal API key, sent as+// "Authorization: <key>" (no "Bearer"). docs/dev/linear-import.md has the details.++export interface LinearCredential {+ apiKey: string;+}++export const LINEAR_GRAPHQL_URL = 'https://api.linear.app/graphql';+const UPLOAD_HOST = 'uploads.linear.app';+// 50 issues with their labels and links stay well inside Linear's 10,000-point+// limit for one query.+const PAGE_SIZE = 50;+const REQUEST_TIMEOUT_MS = 15_000;+const MAX_UPLOAD_REDIRECTS = 3;+// Linear's budgets refill over an hour, so no reset is honoured beyond that.+const MAX_RATE_LIMIT_WAIT_MS = 3_600_000;++const ISSUE_FIELDS = `+ id identifier number title description priority dueDate createdAt updatedAt trashed+ state { id }+ assignee { email }+ cycle { id }+ parent { id identifier team { id } project { id } }+ labels(first: ${PAGE_SIZE}, includeArchived: true) { nodes { id } pageInfo { hasNextPage } }+ attachments(first: ${PAGE_SIZE}, includeArchived: true) { nodes { title url } pageInfo { hasNextPage } }+`;++const STATES_QUERY = `query States($teamId: String!, $after: String) {+ team(id: $teamId) {+ connection: states(first: ${PAGE_SIZE}, after: $after, includeArchived: true) {+ nodes { id name type }+ pageInfo { hasNextPage endCursor }+ }+ }+}`;++const LABELS_QUERY = `query Labels($teamId: ID!, $after: String) {+ connection: issueLabels(+ first: ${PAGE_SIZE}+ after: $after+ includeArchived: true+ filter: { or: [{ team: { id: { eq: $teamId } } }, { team: { null: true } }] }+ ) {+ nodes { id name color isGroup parent { name } }+ pageInfo { hasNextPage endCursor }+ }+}`;++const CYCLES_QUERY = `query Cycles($teamId: String!, $after: String) {+ team(id: $teamId) {+ connection: cycles(first: ${PAGE_SIZE}, after: $after, includeArchived: true) {+ nodes { id number name startsAt endsAt description }+ pageInfo { hasNextPage endCursor }+ }+ }+}`;++const ISSUES_QUERY = `query Issues($filter: IssueFilter!, $after: String) {+ connection: issues(+ first: ${PAGE_SIZE}+ after: $after+ filter: $filter+ includeArchived: true+ orderBy: createdAt+ ) {+ nodes { ${ISSUE_FIELDS} }+ pageInfo { hasNextPage endCursor }+ }+}`;++const ISSUE_QUERY = `query Issue($id: String!) {+ issue(id: $id) { ${ISSUE_FIELDS} }+}`;++const RELATIONS_QUERY = `query Relations($id: String!, $after: String) {+ issue(id: $id) {+ connection: relations(first: ${PAGE_SIZE}, after: $after) {+ nodes { type relatedIssue { id } }+ pageInfo { hasNextPage endCursor }+ }+ }+}`;++const COMMENTS_QUERY = `query Comments($id: String!, $after: String) {+ issue(id: $id) {+ connection: comments(first: ${PAGE_SIZE}, after: $after, includeArchived: true) {+ nodes {+ id body createdAt+ parent { id }+ user { email name }+ botActor { name }+ externalUser { name }+ }+ pageInfo { hasNextPage endCursor }+ }+ }+}`;++interface GraphqlResponse<D> {+ data?: D | null;+ errors?: { message: string; extensions?: { code?: string } }[];+}++type ConnectionData<T> = { connection: LinearConnection<T> };+type TeamConnectionData<T> = { team: ConnectionData<T> };+type IssueConnectionData<T> = { issue: ConnectionData<T> };++const RATE_LIMIT_HEADERS = ['requests', 'complexity', 'endpoint-requests'].map((kind) => ({+ remaining: `x-ratelimit-${kind}-remaining`,+ reset: `x-ratelimit-${kind}-reset`,+}));++// Linear answers a rate-limited request with HTTP 400 and the GraphQL error code+// RATELIMITED (429 is handled the same). Its reset headers are epoch milliseconds;+// the wait runs to the latest reset of a budget that is used up, capped at an hour.+export function linearRateLimitBackoffMs(+ response: { status: number; errorCodes: string[]; headers: Headers },+ nowMs = Date.now(),+): number | null {+ if (response.status !== 429 && !response.errorCodes.includes('RATELIMITED')) return null;+ const resets = RATE_LIMIT_HEADERS.flatMap(({ remaining, reset }) => {+ const left = response.headers.get(remaining);+ const at = Number(response.headers.get(reset));+ return left !== null && Number(left) <= 0 && at > 0 ? [at] : [];+ });+ if (resets.length === 0) return 60_000;+ return Math.min(MAX_RATE_LIMIT_WAIT_MS, Math.max(1000, Math.max(...resets) - nowMs));+}++export type UploadHop =+ { kind: 'download' } | { kind: 'redirect'; url: string } | { kind: 'refused' };++// What one response from the file host means for resolveAttachmentDownload.+export function nextUploadHop(+ currentUrl: string,+ status: number,+ location: string | null,+): UploadHop {+ if (status >= 200 && status < 300) return { kind: 'download' };+ if (status < 300 || status >= 400) return { kind: 'refused' };+ if (!location) throw new AttachmentRejectedError('Linear file storage redirected nowhere');+ const next = new URL(location, currentUrl);+ if (next.protocol !== 'https:') {+ throw new AttachmentRejectedError('Linear file storage redirected to a non-https URL');+ }+ return { kind: 'redirect', url: next.toString() };+}++// The API key goes to Linear's own file host only, never to wherever it redirects.+export function linearUploadHeaders(+ url: string,+ apiKey: string,+): Record<string, string> | undefined {+ return new URL(url).hostname === UPLOAD_HOST ? { Authorization: apiKey } : undefined;+}++// The nested label and link connections are read as one page of 50; more would be+// silently dropped, so the import stops instead.+function assertComplete(issue: LinearIssueNode): LinearIssueNode {+ for (const name of ['labels', 'attachments'] as const) {+ if (issue[name].pageInfo?.hasNextPage) {+ throw new Error(+ `Linear issue ${issue.identifier} has more than ${PAGE_SIZE} ${name}; stopping to avoid a truncated import`,+ );+ }+ }+ return issue;+}++export class LinearReader implements SourceReader {+ // One tick's Create step reads an issue, its comments and its uploads; these keep+ // that to one request each. A reader lives for one tick.+ private readonly issueNodes = new Map<string, Promise<LinearIssueNode>>();+ private readonly commentNodes = new Map<string, Promise<LinearCommentNode[]>>();++ constructor(+ private readonly credential: LinearCredential,+ private readonly scope: LinearScope,+ private readonly fetch: typeof pinnedFetch = pinnedFetch,+ ) {+ if (scope.projectFilter === 'project' && !scope.projectId) {+ throw new Error('Linear scope needs a projectId when projectFilter is "project"');+ }+ }++ async listStates(): Promise<CanonicalState[]> {+ const nodes = await this.paginate<LinearStateNode, TeamConnectionData<LinearStateNode>>(+ STATES_QUERY,+ { teamId: this.scope.teamId },+ (data) => data.team.connection,+ );+ return mapLinearStates(nodes);+ }++ async listLabels(): Promise<CanonicalLabel[]> {+ const nodes = await this.paginate<LinearLabelNode, ConnectionData<LinearLabelNode>>(+ LABELS_QUERY,+ { teamId: this.scope.teamId },+ (data) => data.connection,+ );+ return mapLinearLabels(nodes);+ }++ async listCycles(): Promise<CanonicalCycle[]> {+ const nodes = await this.paginate<LinearCycleNode, TeamConnectionData<LinearCycleNode>>(+ CYCLES_QUERY,+ { teamId: this.scope.teamId },+ (data) => data.team.connection,+ );+ return mapLinearCycles(nodes);+ }++ async listIssues(cursor: string | null): Promise<Page<CanonicalIssue>> {+ const project =+ this.scope.projectFilter === 'none' ? { null: true } : { id: { eq: this.scope.projectId } };+ const data = await this.graphql<ConnectionData<LinearIssueNode>>(ISSUES_QUERY, {+ filter: { team: { id: { eq: this.scope.teamId } }, project },+ after: cursor,+ });+ // includeArchived also returns issues in Linear's trash, which are deleted there.+ const kept = data.connection.nodes.filter((node) => !node.trashed);+ return {+ items: kept.map((node) => mapLinearIssue(assertComplete(node), this.scope)),+ cursor: linearNextCursor(data.connection.pageInfo),+ };+ }++ async getIssue(sourceId: string): Promise<CanonicalIssue> {+ return mapLinearIssue(await this.issueNode(sourceId), this.scope);+ }++ async listIssueRelations(issueSourceId: string): Promise<CanonicalRelation[]> {+ const nodes = await this.paginate<LinearRelationNode, IssueConnectionData<LinearRelationNode>>(+ RELATIONS_QUERY,+ { id: issueSourceId },+ (data) => data.issue.connection,+ );+ return mapLinearRelations(issueSourceId, nodes);+ }++ async listIssueComments(issueSourceId: string): Promise<CanonicalComment[]> {+ return mapLinearComments(await this.commentNodesOf(issueSourceId));+ }++ async listIssueAttachments(issueSourceId: string): Promise<CanonicalAttachment[]> {+ const [issue, comments] = await Promise.all([+ this.issueNode(issueSourceId),+ this.commentNodesOf(issueSourceId),+ ]);+ const bodies = mapLinearComments(comments).map((c) => c.bodyMarkdown);+ return extractLinearUploads(+ issueSourceId,+ [issue.description, ...bodies],+ issue.attachments.nodes,+ );+ }++ // uploads.linear.app needs the API key; whether it serves the file or redirects+ // to signed storage, pinnedFetch follows no redirect, so each hop is taken here.+ // Every hop only reads the response head.+ async resolveAttachmentDownload(+ issueSourceId: string,+ attachmentSourceId: string,+ ): Promise<AttachmentDownload> {+ let url = linearUploadUrl(issueSourceId, attachmentSourceId);+ for (let hop = 0; hop <= MAX_UPLOAD_REDIRECTS; hop++) {+ const headers = linearUploadHeaders(url, this.credential.apiKey);+ const res = await this.fetch(url, {+ headers,+ timeoutMs: REQUEST_TIMEOUT_MS,+ maxBytes: 0,+ truncateBody: true,+ });+ if (res.status === 429) throw new SourceRateLimitedError(60_000, 'Linear rate limit reached');+ const next = nextUploadHop(url, res.status, res.headers.get('location'));+ if (next.kind === 'download') return headers ? { url, headers } : { url };+ if (next.kind === 'refused') {+ throw new AttachmentRejectedError(`Linear file storage answered HTTP ${res.status}`);+ }+ url = next.url;+ }+ throw new AttachmentRejectedError(+ `Linear file storage redirected more than ${MAX_UPLOAD_REDIRECTS} times`,+ );+ }++ private issueNode(id: string): Promise<LinearIssueNode> {+ let node = this.issueNodes.get(id);+ if (!node) {+ node = this.graphql<{ issue: LinearIssueNode }>(ISSUE_QUERY, { id }).then((d) =>+ assertComplete(d.issue),+ );+ this.issueNodes.set(id, node);+ }+ return node;+ }++ private commentNodesOf(id: string): Promise<LinearCommentNode[]> {+ let nodes = this.commentNodes.get(id);+ if (!nodes) {+ nodes = this.paginate<LinearCommentNode, IssueConnectionData<LinearCommentNode>>(+ COMMENTS_QUERY,+ { id },+ (data) => data.issue.connection,+ );+ this.commentNodes.set(id, nodes);+ }+ return nodes;+ }++ private async paginate<T, D>(+ query: string,+ variables: Record<string, unknown>,+ connectionOf: (data: D) => LinearConnection<T>,+ ): Promise<T[]> {+ const all: T[] = [];+ let after: string | null = null;+ do {+ const connection = connectionOf(await this.graphql<D>(query, { ...variables, after }));+ all.push(...connection.nodes);+ after = linearNextCursor(connection.pageInfo);+ } while (after !== null);+ return all;+ }++ private async graphql<D>(query: string, variables: Record<string, unknown>): Promise<D> {+ const res = await this.fetch(LINEAR_GRAPHQL_URL, {+ method: 'POST',+ headers: { Authorization: this.credential.apiKey, 'Content-Type': 'application/json' },+ body: JSON.stringify({ query, variables }),+ timeoutMs: REQUEST_TIMEOUT_MS,+ });+ const body = (await res.json().catch(() => ({}))) as GraphqlResponse<D>;+ const errors = body.errors ?? [];+ const backoff = linearRateLimitBackoffMs({+ status: res.status,+ errorCodes: errors.map((e) => e.extensions?.code ?? ''),+ headers: res.headers,+ });+ if (backoff !== null) throw new SourceRateLimitedError(backoff, 'Linear rate limit reached');+ if (errors.length > 0) throw new Error(`Linear request failed: ${errors[0]!.message}`);+ if (!res.ok || !body.data) throw new Error(`Linear request failed: HTTP ${res.status}`);+ return body.data;+ }+}diff --git a/apps/worker/src/linear-mapping.ts b/apps/worker/src/linear-mapping.tsnew file mode 100644index 00000000..fdcd3dd1--- /dev/null+++ b/apps/worker/src/linear-mapping.ts@@ -0,0 +1,393 @@+import type {+ CanonicalAttachment,+ CanonicalComment,+ CanonicalCycle,+ CanonicalIssue,+ CanonicalLabel,+ CanonicalRelation,+ CanonicalState,+ CanonicalStateCategory,+} from './canonical';++// Pure mapping from Linear's GraphQL shapes (the fields linear-adapter.ts asks for)+// to the canonical import shapes. No network, no @repo/db.++export interface LinearPageInfo {+ hasNextPage: boolean;+ endCursor: string | null;+}++export interface LinearConnection<T> {+ nodes: T[];+ pageInfo: LinearPageInfo;+}++export interface LinearStateNode {+ id: string;+ name: string;+ type: string;+}++export interface LinearLabelNode {+ id: string;+ name: string;+ color: string;+ isGroup: boolean;+ parent: { name: string } | null;+}++export interface LinearCycleNode {+ id: string;+ number: number;+ name: string | null;+ startsAt: string;+ endsAt: string;+ description: string | null;+}++export interface LinearIssueRef {+ id: string;+ identifier: string;+ team: { id: string };+ project: { id: string } | null;+}++export interface LinearLinkNode {+ title: string;+ url: string;+}++export interface LinearIssueNode {+ id: string;+ identifier: string;+ number: number;+ title: string;+ description: string | null;+ priority: number;+ dueDate: string | null;+ createdAt: string;+ updatedAt: string;+ trashed?: boolean | null;+ state: { id: string };+ assignee: { email: string } | null;+ cycle: { id: string } | null;+ parent: LinearIssueRef | null;+ labels: { nodes: { id: string }[]; pageInfo?: { hasNextPage: boolean } };+ attachments: { nodes: LinearLinkNode[]; pageInfo?: { hasNextPage: boolean } };+}++export interface LinearCommentNode {+ id: string;+ body: string;+ createdAt: string;+ parent: { id: string } | null;+ user: { email: string; name: string } | null;+ botActor: { name: string | null } | null;+ externalUser: { name: string } | null;+}++export interface LinearRelationNode {+ type: string;+ relatedIssue: { id: string };+}++// One import job: a team, and either one of its projects or its issues with no project.+export interface LinearScope {+ teamId: string;+ projectFilter: 'project' | 'none';+ projectId: string | null;+}++// Linear's WorkflowState.type. triage and duplicate have no itsaplan category of+// their own; the mapping review step can still change either.+const STATE_CATEGORY_MAP: Record<string, CanonicalStateCategory> = {+ triage: 'backlog',+ backlog: 'backlog',+ unstarted: 'unstarted',+ started: 'started',+ completed: 'completed',+ canceled: 'canceled',+ duplicate: 'canceled',+};++export function linearStateCategory(type: string): CanonicalStateCategory {+ return STATE_CATEGORY_MAP[type] ?? 'backlog';+}++export function mapLinearStates(nodes: LinearStateNode[]): CanonicalState[] {+ return nodes.map((s) => ({+ sourceId: s.id,+ name: s.name,+ category: linearStateCategory(s.type),+ }));+}++// Linear: 0 none, 1 urgent, 2 high, 3 medium, 4 low. itsaplan stores the word, or null.+const PRIORITIES: Record<number, string> = { 1: 'urgent', 2: 'high', 3: 'medium', 4: 'low' };++export function linearPriority(priority: number): string | null {+ return PRIORITIES[priority] ?? null;+}++// A label group is never applied to an issue itself, so only its members are+// imported, each named after its group.+export function mapLinearLabels(nodes: LinearLabelNode[]): CanonicalLabel[] {+ return nodes+ .filter((l) => !l.isGroup)+ .map((l) => ({+ sourceId: l.id,+ name: l.parent ? `${l.parent.name}/${l.name}` : l.name,+ color: l.color,+ }));+}++// The store reuses a cycle by name within a project, so every name in one list must be+// distinct (case-insensitively), or two Linear cycles would merge into one.+export function mapLinearCycles(nodes: LinearCycleNode[]): CanonicalCycle[] {+ const taken = new Set<string>();+ return nodes.map((c) => {+ const base = c.name?.trim() || `Cycle ${c.number}`;+ let name = base;+ for (let n = 1; taken.has(name.toLowerCase()); n++) {+ name = n === 1 ? `${base} (Cycle ${c.number})` : `${base} (Cycle ${c.number}, ${n})`;+ }+ taken.add(name.toLowerCase());+ return mapCycle(c, name);+ });+}++function mapCycle(c: LinearCycleNode, name: string): CanonicalCycle {+ return {+ sourceId: c.id,+ name,+ startDate: c.startsAt.slice(0, 10),+ endDate: c.endsAt.slice(0, 10),+ goal: c.description || undefined,+ };+}++// "https://linear.app/acme/issue/ATO-12/some-slug" and its markdown forms. The+// Rewrite phase can only resolve a bare "ATO-12": inside a URL it would rewrite the+// path and break the link.+const ISSUE_URL = String.raw`https://linear\.app/[\w-]+/issue/([A-Z][A-Z0-9]*-\d+)(?:/[\w%-]*)?(?:[?#][^\s)>\]]*)?`;+const ISSUE_LINK = new RegExp(String.raw`\[([^\]]*)\]\(${ISSUE_URL}\)`, 'g');+const ISSUE_AUTOLINK = new RegExp(String.raw`<${ISSUE_URL}>`, 'g');+const ISSUE_BARE_URL = new RegExp(ISSUE_URL, 'g');++export function linearIssueLinksToIdentifiers(markdown: string): string {+ return markdown+ .replace(ISSUE_LINK, (_m, label: string, identifier: string) => {+ const text = label.trim();+ if (!text || text.startsWith('https://') || text === identifier) return identifier;+ return new RegExp(String.raw`\b${identifier}\b`).test(text)+ ? text+ : `${text} (${identifier})`;+ })+ .replace(ISSUE_AUTOLINK, (_m, identifier: string) => identifier)+ .replace(ISSUE_BARE_URL, (_m, identifier: string) => identifier);+}++const UPLOAD_HOST = 'uploads.linear.app';++export function isLinearUploadUrl(url: string): boolean {+ try {+ const parsed = new URL(url);+ return parsed.protocol === 'https:' && parsed.hostname === UPLOAD_HOST;+ } catch {+ return false;+ }+}++function inScope(ref: LinearIssueRef, scope: LinearScope): boolean {+ if (ref.team.id !== scope.teamId) return false;+ return scope.projectFilter === 'none'+ ? ref.project === null+ : ref.project?.id === scope.projectId;+}++function escapeLinkText(text: string): string {+ return text.replace(/[\\[\]]/g, '\\$&');+}++// The description as written, then the link attachments under "Links", then the+// parent when it lives outside this job (its parent link cannot be kept), then the+// Linear identifier, last, so every imported issue can still be found by it.+export function linearIssueDescription(issue: LinearIssueNode, scope: LinearScope): string {+ const parts: string[] = [];+ const body = linearIssueLinksToIdentifiers(issue.description ?? '').trim();+ if (body) parts.push(body);+ const links = issue.attachments.nodes.filter((a) => !isLinearUploadUrl(a.url));+ if (links.length > 0) {+ const items = links.map((a) => `- [${escapeLinkText(a.title.trim() || a.url)}](${a.url})`);+ parts.push(['## Links', '', ...items].join('\n'));+ }+ if (issue.parent && !inScope(issue.parent, scope)) {+ parts.push(`Parent in Linear: ${issue.parent.identifier}`);+ }+ parts.push(`Imported from Linear: ${issue.identifier}`);+ return parts.join('\n\n');+}++export function mapLinearIssue(issue: LinearIssueNode, scope: LinearScope): CanonicalIssue {+ return {+ sourceId: issue.id,+ sequenceId: issue.number,+ title: issue.title,+ descriptionMarkdown: linearIssueDescription(issue, scope),+ stateSourceId: issue.state.id,+ assigneeEmail: issue.assignee?.email || null,+ labelSourceIds: issue.labels.nodes.map((l) => l.id),+ cycleSourceId: issue.cycle?.id ?? null,+ parentSourceId: issue.parent?.id ?? null,+ priority: linearPriority(issue.priority),+ startDate: null,+ dueDate: issue.dueDate,+ customFields: [],+ createdAt: issue.createdAt,+ updatedAt: issue.updatedAt,+ };+}++// A comment from an integration or a bot has no user, so no email to match a+// member by; it keeps the bot's or the external author's name.+export function linearCommentAuthor(comment: LinearCommentNode): {+ authorEmail: string | null;+ authorName: string;+} {+ if (comment.user) {+ return {+ authorEmail: comment.user.email || null,+ authorName: comment.user.name || comment.user.email,+ };+ }+ return {+ authorEmail: null,+ authorName: comment.botActor?.name || comment.externalUser?.name || 'Linear',+ };+}++// Oldest first: the Create phase links a reply to its parent only when the parent+// was created before it.+export function mapLinearComments(nodes: LinearCommentNode[]): CanonicalComment[] {+ return [...nodes]+ .sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt))+ .map((c) => ({+ sourceId: c.id,+ ...linearCommentAuthor(c),+ bodyMarkdown: linearIssueLinksToIdentifiers(c.body),+ createdAt: c.createdAt,+ replyToSourceId: c.parent?.id ?? null,+ }));+}++// Issue.relations lists only the relations this issue owns, each once; the same+// relation seen from the other issue (inverseRelations) is never read. "similar" is a+// suggestion Linear makes, not a link anyone created.+const RELATION_KIND_MAP: Record<string, CanonicalRelation['kind']> = {+ blocks: 'blocks',+ duplicate: 'duplicates',+ related: 'relates',+};++export function mapLinearRelations(+ issueSourceId: string,+ nodes: LinearRelationNode[],+): CanonicalRelation[] {+ return nodes.flatMap((r) => {+ const kind = RELATION_KIND_MAP[r.type];+ if (!kind) return [];+ return [{ kind, sourceIssueSourceId: issueSourceId, targetIssueSourceId: r.relatedIssue.id }];+ });+}++export function linearNextCursor(pageInfo: LinearPageInfo): string | null {+ if (!pageInfo.hasNextPage) return null;+ if (!pageInfo.endCursor) {+ throw new Error(+ 'Linear reported another page but sent no end cursor; stopping to avoid a truncated import',+ );+ }+ return pageInfo.endCursor;+}++const UPLOAD_LINK = /\[([^\]]*)\]\((https:\/\/uploads\.linear\.app\/[^)\s]+)\)/g;+const UPLOAD_URL = /https:\/\/uploads\.linear\.app\/[^\s)<>\]"'`]+/g;++// The attachment's import_record source id: the upload URL, scoped to its issue, so+// the same file referenced from two issues is attached to both.+export function linearUploadSourceId(issueSourceId: string, url: string): string {+ return `${issueSourceId} ${url}`;+}++export function linearUploadUrl(issueSourceId: string, attachmentSourceId: string): string {+ const prefix = `${issueSourceId} `;+ const url = attachmentSourceId.startsWith(prefix) ? attachmentSourceId.slice(prefix.length) : '';+ if (!isLinearUploadUrl(url)) {+ throw new Error(`"${attachmentSourceId}" is not a Linear upload of issue ${issueSourceId}`);+ }+ return url;+}++export function contentTypeForFilename(filename: string): string {+ return Bun.file(filename).type.split(';')[0]!;+}++function lastPathSegment(url: string): string {+ return new URL(url).pathname.split('/').filter(Boolean).pop() ?? 'file';+}++// The Attachments phase reuses a file already on the issue under the same name, so+// three screenshots pasted as "image.png" would otherwise become one.+function uniqueFilenames(names: string[]): string[] {+ const seen = new Map<string, number>();+ return names.map((name) => {+ const key = name.toLowerCase();+ const count = (seen.get(key) ?? 0) + 1;+ seen.set(key, count);+ if (count === 1) return name;+ const dot = name.lastIndexOf('.');+ let n = count;+ let candidate = '';+ do {+ candidate = dot > 0 ? `${name.slice(0, dot)} (${n})${name.slice(dot)}` : `${name} (${n})`;+ n++;+ } while (seen.has(candidate.toLowerCase()));+ seen.set(candidate.toLowerCase(), 1);+ return candidate;+ });+}++// Files uploaded into Linear text (description, then comments, then upload-hosted+// link attachments), first mention wins. Linear reports no size or type for them:+// the type comes from the file name and the size check waits for the real bytes.+export function extractLinearUploads(+ issueSourceId: string,+ texts: (string | null)[],+ links: LinearLinkNode[],+): CanonicalAttachment[] {+ const labels = new Map<string, string>();+ for (const text of texts) {+ if (!text) continue;+ for (const [, label, url] of text.matchAll(UPLOAD_LINK)) {+ if (!labels.has(url!)) labels.set(url!, label!.trim());+ }+ // Bare URLs: trailing sentence punctuation is not part of the URL. Link+ // destinations are exact, so they are removed before this scan.+ for (const [match] of text.replace(UPLOAD_LINK, ' ').matchAll(UPLOAD_URL)) {+ const url = match.replace(/[.,;:!?]+$/, '');+ if (!labels.has(url)) labels.set(url, '');+ }+ }+ for (const link of links) {+ if (isLinearUploadUrl(link.url) && !labels.has(link.url))+ labels.set(link.url, link.title.trim());+ }+ const urls = [...labels.keys()];+ const names = uniqueFilenames(urls.map((url) => labels.get(url) || lastPathSegment(url)));+ return urls.map((url, i) => ({+ sourceId: linearUploadSourceId(issueSourceId, url),+ filename: names[i]!,+ contentType: contentTypeForFilename(names[i]!),+ sizeBytes: 0,+ }));+}diff --git a/apps/worker/src/reader.ts b/apps/worker/src/reader.tsindex 5ebe6652..ca7f2908 100644--- a/apps/worker/src/reader.ts+++ b/apps/worker/src/reader.ts@@ -8,6 +8,14 @@ import type {CanonicalAttachment,} from './canonical';+// Thrown when a job's source has no entry in the import source registry. No retry+// can fix it, so the worker fails the job at once instead of retrying it.+export class UnsupportedImportSourceError extends Error {+ constructor(jobId: number, source: string) {+ super(`import job ${jobId} has unsupported source "${source}"`);+ }+}+// Thrown by a source adapter when the source's rate limit is reached. The worker// reschedules the job after retryAfterMs; a rate limit is waited out and does not// count toward the attempt limit.diff --git a/docs/dev/linear-import.md b/docs/dev/linear-import.mdnew file mode 100644index 00000000..345be2cd--- /dev/null+++ b/docs/dev/linear-import.md@@ -0,0 +1,103 @@+# The Linear import source++How the Linear source plugs into the import pipeline described in+[plane-import.md](plane-import.md). The phases, resumability, de-duplication and rate-limit+handling are the same for every source; this file covers what is specific to Linear. The user+guide is [importing-from-linear.md](../importing-from-linear.md).++## Shape++- `apps/worker/src/linear-mapping.ts` — pure mapping from the GraphQL shapes to the canonical+ ones (states, labels, cycles, issues, comments, relations, uploads), unit-tested directly.+- `apps/worker/src/linear-adapter.ts` — `LinearReader`, the `SourceReader` for Linear: the+ queries, paging, the rate-limit check, and the upload download hops.+- `apps/worker/src/import-sources.ts` — the `linear` entry: credential `{ apiKey }`, config+ `{ teamId, teamKey, projectFilter: 'project' | 'none', projectId }`, and `teamKey` as the+ Rewrite prefix.+- `apps/api/src/modules/import-export/linear.ts` — the key check (teams with their projects),+ the states preview, and the Linear fields of `POST /import-jobs` (`source: 'linear'`).+- `apps/web/src/features/settings/components/import-export/SettingsImportExportLinear*.tsx` —+ the Linear tab; the mapping review is shared with Plane.++## Requests++Every request is a `POST` to the fixed `https://api.linear.app/graphql` through `pinnedFetch`,+with the personal API key as `Authorization: <key>` (no `Bearer`; an invalid key answers HTTP+401 with the GraphQL error code `AUTHENTICATION_ERROR`). No user-supplied URL is fetched.++| Reader method | Query |+|---|---|+| `listStates` | `team(id).states`, archived included |+| `listLabels` | `issueLabels` filtered to the team's labels and the workspace's (`team: { null: true }`), archived included; groups dropped, members named `Group/Name` |+| `listCycles` | `team(id).cycles`, archived included |+| `listIssues` | `issues(filter: { team, project: { id: { eq } } \| { null: true } }, includeArchived: true, orderBy: createdAt)`; an issue with `trashed` set (in Linear's trash) is dropped |+| `getIssue` | `issue(id)` |+| `listIssueRelations` | `issue(id).relations` — never `inverseRelations`, so each relation is read once, from the issue that owns it |+| `listIssueComments` | `issue(id).comments`, archived included, sorted oldest first |+| `listIssueAttachments` | the issue and its comments (the same two requests, cached for the tick), then the uploads found in their text |++Connections are read 50 at a time and paging stops only when `pageInfo.hasNextPage` is false.+An issue's nested labels and link attachments (archived ones included) are read as one page+of 50; when either reports `hasNextPage`, `assertComplete` throws an error naming the issue+("stopping to avoid a truncated import") rather than dropping the rest. One issue with its+labels and link attachments costs about 125+complexity points, so a page of 50 stays well inside Linear's 10,000-point limit for a single+query. A reader lives for one tick and caches the issue and comment reads of that tick, so the+Create step costs two requests per issue.++## Scope and source checks++`LinearReader` throws when the scope is `projectFilter: 'project'` without a `projectId`; the+API answers 400 for the same input when creating a job. A job whose `source` is not in the+registry fails at once with `UnsupportedImportSourceError`, with no retry.++## Rate limits++Linear answers a rate-limited request with HTTP 400 (sometimes 429) and the GraphQL error+code `RATELIMITED`. `linearRateLimitBackoffMs` turns that into `SourceRateLimitedError`, waiting+until the latest `X-RateLimit-*-Reset` (epoch milliseconds) of a budget whose `-Remaining`+is 0, capped at one hour (Linear's window), or one minute when no header says. The worker+reschedules the job for that reset time and records `last_error = 'rate limited'`. A rate+limit never fails the job by itself.++## Text++- Linear issue links (`https://linear.app/<workspace>/issue/ATO-12/<slug>`, bare, autolinked,+ or as a Markdown link) become the bare identifier `ATO-12`, so the Rewrite phase can resolve+ them; a rewritten URL would be a broken link.+- The description gets, in order: Linear's text, a `## Links` list of the link attachments+ that are not uploads, `Parent in Linear: <identifier>` when the parent is outside the job's+ team and project filter, and `Imported from Linear: <identifier>` last.+- An issue key directly after a `/` is not matched (`cross-reference.ts`), so a URL path is+ never rewritten.+- Rewrite leaves an issue's mention of itself as written (`rewriteCrossReferences` in+ `import-worker.ts`), which keeps the `Imported from Linear` line intact. A mention of an issue+ another job imported is left as written too, because `import_record` lookups are per job.++## Uploads++Files uploaded into Linear text live at `https://uploads.linear.app/...` and need the API key.+`extractLinearUploads` collects them from the description, then the comments, then link+attachments hosted there, first mention winning; a bare URL followed by sentence punctuation+(`.,;:!?`) is read without it. The attachment's source id is `"<issue id> <upload URL>"`, so+the same file referenced from two issues is attached to both.+Linear reports no size or type: the type comes from the file name (Bun's MIME table) and+`sizeBytes` is 0, so the size check is the download's own byte limit: a larger file stops+downloading there and is skipped (`ResponseTooLargeError` becomes `AttachmentRejectedError`).+Repeated names on one issue get ` (2)`, ` (3)` before the extension (skipping any name already+taken, compared case-insensitively), because the store reuses an attachment with the same+filename on the same issue.++`pinnedFetch` follows no redirect and `downloadAttachment` refuses anything but 2xx, so+`resolveAttachmentDownload` takes the hops itself: a `GET` that reads only the response head+(`maxBytes: 0, truncateBody: true`), up to three redirects, `https` only. The `Authorization`+header is sent only while the host is `uploads.linear.app`, never to the storage host a+redirect points at. A 2xx returns the final URL (with the key when that URL is still on+`uploads.linear.app`); a 429 is a rate limit; any other status, a redirect without a location,+or a fourth redirect is an `AttachmentRejectedError`, logged and skipped.++## Cycles++The store reuses a cycle by name within a project, so `mapLinearCycles` makes every name in a+list distinct, case-insensitively: an unnamed cycle is `Cycle <number>`, and a repeated name+becomes `<name> (Cycle <number>)`, then `<name> (Cycle <number>, 2)` and so on.diff --git a/docs/dev/plane-import.md b/docs/dev/plane-import.mdindex 2ca77879..6f8b13cf 100644--- a/docs/dev/plane-import.md+++ b/docs/dev/plane-import.md@@ -14,14 +14,16 @@ returns.local id mapping, the idempotency and resume primitive).- `apps/worker/src/{canonical,reader,import-sources,plane-adapter,import-store,import-worker}.ts`— the `SourceReader` port, the per-source registry the worker dispatches on- `import_job.source` through, the only implementation (Plane), and the phase state machine+ `import_job.source` through, the Plane implementation, and the phase state machine(discover → create → link → rewrite → attachments → done) that drives a job one bounded chunk pertick.- `packages/storage` and `packages/db/src/domains/storage.ts` — object storage and uploadlimits, shared with `apps/api` so an imported attachment is held to the same rules aninteractive upload is.- `apps/api/src/modules/import-export/` — create/test-connection/plane-preview/export/status/- pause/resume/cancel routes.+ pause/resume/cancel routes, and linear-test-connection/linear-preview.+- The Linear source (`linear-adapter.ts`, `linear-mapping.ts`, the api's `linear.ts`, the+ Linear tab) has its own notes: [linear-import.md](linear-import.md).- `apps/web/src/features/settings/components/import-export/` — the Settings page.## Export: a JSON snapshot, not a live syncdiff --git a/docs/importing-from-linear.md b/docs/importing-from-linear.mdnew file mode 100644index 00000000..2556f0a5--- /dev/null+++ b/docs/importing-from-linear.md@@ -0,0 +1,154 @@+# Importing from Linear++Project Settings → Import/Export connects a project to a Linear workspace with a personal API+key, pulls one Linear team's project (or that team's issues that belong to no project) into+it, and shows the job's progress while it runs. This page describes exactly what it brings+over, what it does not, and what to expect while it runs. Read the limitations before+importing anything you care about — some of them affect data you may not notice is missing+until later.++## What you need++- A Linear personal API key. In Linear, open Settings → Security & access → Personal API+ keys and create one; read-only access is enough. The key is stored encrypted and is only+ ever used by the import itself — it is never shown again after you submit it, and it is+ deleted once the job finishes or is canceled.+- The people whose assignments and comments should keep their names must already be members+ of this project, with the same email address they use in Linear.++## Steps++1. Open the project's **Settings → Import/Export** and choose **Linear** under Source.+2. Paste the API key, then **Test connection**. This checks the key live against Linear and+ lists the teams it can see, each with its projects — nothing is saved yet at this point.+3. Pick the team, then one of its projects or **Issues with no project**. The team's workflow+ states appear for review (see below), with a choice for how to handle an unmatched+ assignee or comment author.+4. **Start import.** The job appears in the list below, in the background. You can leave the+ page and come back — it keeps running, and you can pause, resume, or cancel it from the+ same list at any time.++One job imports one project of one team. To bring a whole team over, run one job per Linear+project, plus one for the team's issues with no project.++## What is imported++- **Issues** — every issue in the project you picked, including completed, canceled, and+ archived ones: title, description (Linear already stores Markdown, so it is kept as+ written), state, labels, cycle, priority, due date, the parent issue if it is a sub-issue+ in the same import, and the dates the issue was created and last updated in Linear. If+ this project archives completed or canceled issues automatically, an imported issue whose+ last update in Linear is older than that threshold is archived on the next sweep.+- **The Linear identifier.** Every imported issue's description ends with a line such as+ `Imported from Linear: ATO-505`, so you can still find an issue by its Linear identifier.+ That line is never rewritten to this project's identifier.+- **A sub-issue whose parent is not part of the same import** (it is in another project or+ another team) cannot keep its parent link. Its description gets a line such as+ `Parent in Linear: ATO-12` just above the identifier line instead.+- **Priority** — Urgent, High, Medium, and Low keep their level; No priority stays empty.+- **Assignees and comment authors** — matched to an existing project member by email. It is+ never assigned to the wrong person, and no placeholder account is created; what happens+ when no member has that email is a choice you make in the mapping review step below.+- **Comments** — body, reply threading, original author, and original date. A comment+ posted by an integration (GitHub, Slack, and so on) keeps the integration's name as its+ author.+- **Labels** — created if they do not already exist by that name, with their Linear color.+ A label inside a label group is named after its group, for example `kind/bug`. Every label+ of the team and every workspace-wide label is created, whether or not an imported issue+ uses it.+- **Workflow states** — created if they do not already exist by that name. Linear's Triage+ states map to Backlog and its Duplicate states to Canceled; you can change either in the+ mapping review.+- **Cycles** — with their start and end dates. A cycle with no name is named after its+ number, for example `Cycle 3`. Two cycles with the same name are kept apart: the repeated+ name becomes `<name> (Cycle <number>)`. Every cycle of the team is created, whether or not an+ imported issue belongs to it.+- **Issue relations** — "blocks", "related", and "duplicate", each once and in its original+ direction, when both issues are part of the same import.+- **Links attached to an issue** (a GitHub pull request, a URL, including archived link+ attachments) — listed at the end of the description under a **Links** heading.+- **Files uploaded into a description or a comment** — downloaded with your API key and+ attached to the same issue. The link in the text stays as Linear wrote it. Several files+ with the same name on one issue (three screenshots all called `image.png`) are kept apart+ as `image.png`, `image (2).png`, `image (3).png`; the suffix is never one that another file+ on that issue already uses. A link to an upload that sits right before a full stop, comma,+ or other sentence punctuation is still found. A file is skipped, not imported, when it+ is larger than this instance's own upload limit, when its type is one this instance does+ not accept, or when Linear's file storage answers the download with an error. The type is+ read from the file's name, so a file whose name has no extension counts as a generic+ binary file, which the default settings do not accept. A skipped file is only noted in the+ server log, not shown anywhere in this screen today. Re-running an import reuses a file+ already attached with the same name on the same issue, rather than attaching it a second+ time.+- **Mentions of other issues.** A link to a Linear issue inside a description or comment is+ turned into that issue's identifier, such as `ATO-12`. An identifier that directly follows+ a `/`, as in the path of a URL, is not changed. When that issue was imported by the+ same job, the identifier is then rewritten to this project's own identifier for it. When it+ was not, `ATO-12` stays as it is, and searching for it finds the issue wherever it was+ imported, by its `Imported from Linear` line.++## What is not imported++- **Estimates, SLAs, reactions, subscribers (watchers), and activity history.**+- **Completed and canceled times.** An issue keeps its state, which places it in the right+ column, but not the time it was completed or canceled.+- **Project milestones, project updates, documents, initiatives, and custom views.** A Linear+ project's own name, description, and status are not copied either — only its issues.+- **Archived state.** An archived Linear issue is imported as an ordinary issue in its state.+- **Deleted issues** — an issue in Linear's trash is left out.+- **Start dates** — Linear issues have none.+- **"Similar" relations** — Linear suggests these itself; nobody created them.+- **Files outside Linear's own file storage.** A link attachment pointing anywhere else is+ listed under Links, not downloaded.++## Limits on labels and links++An issue can have at most 50 labels and at most 50 link attachments. When an issue has more,+the import stops with an error that names the issue and says it is stopping to avoid a+truncated import, instead of importing the issue without the rest.++## Reviewing the mapping before you import++After you pick the team and project, the team's workflow states are shown with the category+itsaplan would automatically map each one to: Linear's own Backlog, Unstarted, Started,+Completed, and Canceled types map to the same categories, Triage to Backlog, and Duplicate to+Canceled. Change any row that reads wrong before starting the import — a state you don't+change keeps the automatic mapping.++The same screen has one more choice: what happens to an assignee or comment author whose+email matches no member of this project. "Leave unassigned" (the default) imports the issue+or comment anyway, with that field empty. "Skip the assignment or comment" leaves an issue's+assignee empty the same way, but drops a comment entirely rather than importing it with no+attributed author. A comment from an integration has no email to match, so it is always+imported under the integration's name.++## Rate limits are real, and the import waits them out++Linear allows each API key a fixed number of requests, and of query complexity, per hour. A+project of any real size can reach that limit, and the job pauses to wait it out — you will+see "The source's rate limit was reached. Retrying in Ns." in the job list when this happens.+This is normal, not a failure; the import resumes on its own once Linear's limit resets,+which can take up to an hour. A large project can take a long time to finish for this reason+alone.++## Pausing, resuming, canceling, and running it again++Pausing and resuming continues from where the job left off. Canceling stops it where it+stands — issues already created stay created, nothing is rolled back.++Starting a *new* import of the same Linear project reuses what a previous run already+created instead of duplicating it: a state, cycle, or issue is matched by name (issue titles+case- and whitespace-insensitively) against what is already in the project, and a comment is+matched by its exact body and timestamp on the matched issue. Labels always dedupe this way+too. Nothing about an existing match is overwritten.++This is a name/content match, not a record of which import created what, so an issue you+created by hand before importing, with exactly the title of an issue in Linear, is treated as+the same issue and gets Linear's labels, comments, and other fields attached to it rather+than getting a second copy. Within one import, two different Linear issues with the same+title stay two issues, and two comments with the same text and time stay two comments.++## Other sources++[Importing from Plane](importing-from-plane.md) describes the Plane source. Jira and Trello+are not available.diff --git a/docs/importing-from-plane.md b/docs/importing-from-plane.mdindex 8d6f313d..2eec8158 100644--- a/docs/importing-from-plane.md+++ b/docs/importing-from-plane.md@@ -88,8 +88,8 @@ attributed author.## Rate limits are real, and the import waits them outPlane limits how many requests it will answer per minute. A project of any real size will-run into that limit, and the job pauses to wait it out — you will see "Plane's rate limit-was reached, retrying in Ns" in the job list when this happens. This is normal, not a+run into that limit, and the job pauses to wait it out — you will see "The source's rate+limit was reached. Retrying in Ns." in the job list when this happens. This is normal, not afailure; the import resumes on its own once the wait is over. A large project can take along time to finish for this reason alone.@@ -122,7 +122,7 @@ snapshot, readable on its own, using this project's own identifiers rather thanids. This is a download, not a live sync: it does not write anywhere, including back intoPlane, and nothing is scheduled or kept running.-## Only Plane, only import+## Other sources-Plane is the only supported source to import from today — Linear and Jira are not-available.+[Importing from Linear](importing-from-linear.md) describes the Linear source. Jira and Trello+are not available.diff --git a/packages/db/drizzle/0143_import_job_linear_source.sql b/packages/db/drizzle/0143_import_job_linear_source.sqlnew file mode 100644index 00000000..82627226--- /dev/null+++ b/packages/db/drizzle/0143_import_job_linear_source.sql@@ -0,0 +1,2 @@+ALTER TABLE "import_job" DROP CONSTRAINT "import_job_source_check";--> statement-breakpoint+ALTER TABLE "import_job" ADD CONSTRAINT "import_job_source_check" CHECK ("import_job"."source" IN ('plane', 'linear'));\ No newline at end of filediff --git a/packages/db/drizzle/meta/0143_snapshot.json b/packages/db/drizzle/meta/0143_snapshot.jsonnew file mode 100644index 00000000..db6aad2a--- /dev/null+++ b/packages/db/drizzle/meta/0143_snapshot.json@@ -0,0 +1,11377 @@+{+ "id": "c78e9e48-c24d-4b18-a209-781a53fca222",+ "prevId": "aa15e1bf-3ddb-45a5-82a9-be30650c34eb",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 100+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_access_token": {+ "name": "oauth_access_token",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "oauthAccessToken_clientId_idx": {+ "name": "oauthAccessToken_clientId_idx",+ "columns": [+ {+ "expression": "client_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthAccessToken_userId_idx": {+ "name": "oauthAccessToken_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "oauth_access_token_client_id_oauth_application_client_id_fk": {+ "name": "oauth_access_token_client_id_oauth_application_client_id_fk",+ "tableFrom": "oauth_access_token",+ "tableTo": "oauth_application",+ "columnsFrom": [+ "client_id"+ ],+ "columnsTo": [+ "client_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauth_access_token_user_id_user_id_fk": {+ "name": "oauth_access_token_user_id_user_id_fk",+ "tableFrom": "oauth_access_token",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauth_access_token_access_token_unique": {+ "name": "oauth_access_token_access_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "access_token"+ ]+ },+ "oauth_access_token_refresh_token_unique": {+ "name": "oauth_access_token_refresh_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "refresh_token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_application": {+ "name": "oauth_application",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "client_secret": {+ "name": "client_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "redirect_urls": {+ "name": "redirect_urls",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "oauthApplication_userId_idx": {+ "name": "oauthApplication_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "oauth_application_user_id_user_id_fk": {+ "name": "oauth_application_user_id_user_id_fk",+ "tableFrom": "oauth_application",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauth_application_client_id_unique": {+ "name": "oauth_application_client_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "client_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_consent": {+ "name": "oauth_consent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "scopes": {+ "name": "scopes",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "consent_given": {+ "name": "consent_given",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "oauthConsent_clientId_idx": {+ "name": "oauthConsent_clientId_idx",+ "columns": [+ {+ "expression": "client_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthConsent_userId_idx": {+ "name": "oauthConsent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "oauth_consent_client_id_oauth_application_client_id_fk": {+ "name": "oauth_consent_client_id_oauth_application_client_id_fk",+ "tableFrom": "oauth_consent",+ "tableTo": "oauth_application",+ "columnsFrom": [+ "client_id"+ ],+ "columnsTo": [+ "client_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauth_consent_user_id_user_id_fk": {+ "name": "oauth_consent_user_id_user_id_fk",+ "tableFrom": "oauth_consent",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.passkey": {+ "name": "passkey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "public_key": {+ "name": "public_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "credential_id": {+ "name": "credential_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "counter": {+ "name": "counter",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "device_type": {+ "name": "device_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "backed_up": {+ "name": "backed_up",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "transports": {+ "name": "transports",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "aaguid": {+ "name": "aaguid",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "passkey_userId_idx": {+ "name": "passkey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "passkey_credentialID_idx": {+ "name": "passkey_credentialID_idx",+ "columns": [+ {+ "expression": "credential_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "passkey_user_id_user_id_fk": {+ "name": "passkey_user_id_user_id_fk",+ "tableFrom": "passkey",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "display_username": {+ "name": "display_username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'user'"+ },+ "active": {+ "name": "active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ },+ "user_username_unique": {+ "name": "user_username_unique",+ "nullsNotDistinct": false,+ "columns": [+ "username"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_event": {+ "name": "agent_chat_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "bigserial",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_event_message_idx": {+ "name": "agent_chat_event_message_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_event_message_id_agent_chat_message_id_fk": {+ "name": "agent_chat_event_message_id_agent_chat_message_id_fk",+ "tableFrom": "agent_chat_event",+ "tableTo": "agent_chat_message",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_favorite": {+ "name": "agent_chat_favorite",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "agent_chat_favorite_user_id_user_id_fk": {+ "name": "agent_chat_favorite_user_id_user_id_fk",+ "tableFrom": "agent_chat_favorite",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_favorite_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_favorite_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_favorite",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_chat_favorite_user_id_thread_id_pk": {+ "name": "agent_chat_favorite_user_id_thread_id_pk",+ "columns": [+ "user_id",+ "thread_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_message": {+ "name": "agent_chat_message",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_message_thread_idx": {+ "name": "agent_chat_message_thread_idx",+ "columns": [+ {+ "expression": "thread_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_chat_message_due_idx": {+ "name": "agent_chat_message_due_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_message_thread_id_agent_chat_thread_id_fk": {+ "name": "agent_chat_message_thread_id_agent_chat_thread_id_fk",+ "tableFrom": "agent_chat_message",+ "tableTo": "agent_chat_thread",+ "columnsFrom": [+ "thread_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_message_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_message_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_message",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_chat_message_role_check": {+ "name": "agent_chat_message_role_check",+ "value": "\"agent_chat_message\".\"role\" IN ('user', 'assistant')"+ },+ "agent_chat_message_status_check": {+ "name": "agent_chat_message_status_check",+ "value": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming', 'success', 'failed', 'canceled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_chat_thread": {+ "name": "agent_chat_thread",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cli_session_id": {+ "name": "cli_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_thread_agent_user_idx": {+ "name": "agent_chat_thread_agent_user_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_thread_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_thread_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_thread",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_thread_user_id_user_id_fk": {+ "name": "agent_chat_thread_user_id_user_id_fk",+ "tableFrom": "agent_chat_thread",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_usage": {+ "name": "agent_chat_usage",+ "schema": "",+ "columns": {+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_usage_agent_idx": {+ "name": "agent_chat_usage_agent_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_usage_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_usage_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_usage",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_field_trigger": {+ "name": "agent_field_trigger",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "delay_sec": {+ "name": "delay_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 120+ }+ },+ "indexes": {+ "agent_field_trigger_field_idx": {+ "name": "agent_field_trigger_field_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_field_trigger_agent_id_ai_agent_id_fk": {+ "name": "agent_field_trigger_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_field_trigger",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_field_trigger_field_id_custom_field_id_fk": {+ "name": "agent_field_trigger_field_id_custom_field_id_fk",+ "tableFrom": "agent_field_trigger",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_field_trigger_agent_id_field_id_pk": {+ "name": "agent_field_trigger_agent_id_field_id_pk",+ "columns": [+ "agent_id",+ "field_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_field_trigger_delay_check": {+ "name": "agent_field_trigger_delay_check",+ "value": "\"agent_field_trigger\".\"delay_sec\" >= 0 AND \"agent_field_trigger\".\"delay_sec\" <= 86400"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_run": {+ "name": "agent_run",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "schedule_id": {+ "name": "schedule_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'delegation'"+ },+ "scheduled_for": {+ "name": "scheduled_for",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "source_activity_id": {+ "name": "source_activity_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "output": {+ "name": "output",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_run_schedule_fire_uq": {+ "name": "agent_run_schedule_fire_uq",+ "columns": [+ {+ "expression": "schedule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scheduled_for",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_run_due_idx": {+ "name": "agent_run_due_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_run_schedule_idx": {+ "name": "agent_run_schedule_idx",+ "columns": [+ {+ "expression": "schedule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_run_project_idx": {+ "name": "agent_run_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_run_agent_id_ai_agent_id_fk": {+ "name": "agent_run_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_project_id_project_id_fk": {+ "name": "agent_run_project_id_project_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_issue_id_issue_id_fk": {+ "name": "agent_run_issue_id_issue_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_schedule_id_agent_schedule_id_fk": {+ "name": "agent_run_schedule_id_agent_schedule_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "agent_schedule",+ "columnsFrom": [+ "schedule_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_source_activity_id_issue_activity_id_fk": {+ "name": "agent_run_source_activity_id_issue_activity_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "source_activity_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_run_status_check": {+ "name": "agent_run_status_check",+ "value": "\"agent_run\".\"status\" IN ('pending', 'success', 'failed', 'canceled')"+ },+ "agent_run_trigger_check": {+ "name": "agent_run_trigger_check",+ "value": "\"agent_run\".\"trigger\" IN ('mention', 'delegation', 'field', 'schedule', 'manual')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_schedule": {+ "name": "agent_schedule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "cron": {+ "name": "cron",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "next_run_at": {+ "name": "next_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "last_run_at": {+ "name": "last_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_schedule_due_idx": {+ "name": "agent_schedule_due_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_run_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_schedule_agent_idx": {+ "name": "agent_schedule_agent_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_schedule_project_idx": {+ "name": "agent_schedule_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_schedule_agent_id_ai_agent_id_fk": {+ "name": "agent_schedule_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_schedule",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_schedule_project_id_project_id_fk": {+ "name": "agent_schedule_project_id_project_id_fk",+ "tableFrom": "agent_schedule",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_schedule_project_id_agent_id_name_unique": {+ "name": "agent_schedule_project_id_agent_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "agent_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "agent_schedule_status_check": {+ "name": "agent_schedule_status_check",+ "value": "\"agent_schedule\".\"status\" IN ('active', 'paused')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_skill": {+ "name": "agent_skill",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_url": {+ "name": "source_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "s3_prefix": {+ "name": "s3_prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "files": {+ "name": "files",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_skill_team_idx": {+ "name": "agent_skill_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_skill_team_id_team_id_fk": {+ "name": "agent_skill_team_id_team_id_fk",+ "tableFrom": "agent_skill",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_skill_team_id_name_unique": {+ "name": "agent_skill_team_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "agent_skill_source_check": {+ "name": "agent_skill_source_check",+ "value": "\"agent_skill\".\"source\" IN ('upload', 'inline', 'github')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_skill_link": {+ "name": "agent_skill_link",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "skill_id": {+ "name": "skill_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_skill_link_skill_idx": {+ "name": "agent_skill_link_skill_idx",+ "columns": [+ {+ "expression": "skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_skill_link_agent_id_ai_agent_id_fk": {+ "name": "agent_skill_link_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_skill_link",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_skill_link_skill_id_agent_skill_id_fk": {+ "name": "agent_skill_link_skill_id_agent_skill_id_fk",+ "tableFrom": "agent_skill_link",+ "tableTo": "agent_skill",+ "columnsFrom": [+ "skill_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_skill_link_agent_id_skill_id_pk": {+ "name": "agent_skill_link_agent_id_skill_id_pk",+ "columns": [+ "agent_id",+ "skill_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_tool": {+ "name": "agent_tool",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "tool_key": {+ "name": "tool_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "credential_id": {+ "name": "credential_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_tool_team_idx": {+ "name": "agent_tool_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_tool_credential_idx": {+ "name": "agent_tool_credential_idx",+ "columns": [+ {+ "expression": "credential_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_tool_team_id_team_id_fk": {+ "name": "agent_tool_team_id_team_id_fk",+ "tableFrom": "agent_tool",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_tool_credential_id_integration_credential_id_fk": {+ "name": "agent_tool_credential_id_integration_credential_id_fk",+ "tableFrom": "agent_tool",+ "tableTo": "integration_credential",+ "columnsFrom": [+ "credential_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_tool_team_id_tool_key_credential_id_unique": {+ "name": "agent_tool_team_id_tool_key_credential_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "tool_key",+ "credential_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_tool_link": {+ "name": "agent_tool_link",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "agent_tool_id": {+ "name": "agent_tool_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_tool_link_tool_idx": {+ "name": "agent_tool_link_tool_idx",+ "columns": [+ {+ "expression": "agent_tool_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_tool_link_agent_id_ai_agent_id_fk": {+ "name": "agent_tool_link_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_tool_link",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_tool_link_agent_tool_id_agent_tool_id_fk": {+ "name": "agent_tool_link_agent_tool_id_agent_tool_id_fk",+ "tableFrom": "agent_tool_link",+ "tableTo": "agent_tool",+ "columnsFrom": [+ "agent_tool_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_tool_link_agent_id_agent_tool_id_pk": {+ "name": "agent_tool_link_agent_id_agent_tool_id_pk",+ "columns": [+ "agent_id",+ "agent_tool_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_agent": {+ "name": "ai_agent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "model_credential_id": {+ "name": "model_credential_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tools": {+ "name": "tools",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "temperature": {+ "name": "temperature",+ "type": "double precision",+ "primaryKey": false,+ "notNull": false+ },+ "max_steps": {+ "name": "max_steps",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_on_mention": {+ "name": "trigger_on_mention",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "trigger_on_assign": {+ "name": "trigger_on_assign",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "delegation_delay_sec": {+ "name": "delegation_delay_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 120+ },+ "api_key_ciphertext": {+ "name": "api_key_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "api_key_iv": {+ "name": "api_key_iv",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "api_key_auth_tag": {+ "name": "api_key_auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "memory_enabled": {+ "name": "memory_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "memory_last_messages": {+ "name": "memory_last_messages",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "runner_scope": {+ "name": "runner_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'team'"+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "ai_agent_team_username_uq": {+ "name": "ai_agent_team_username_uq",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lower(\"username\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ai_agent_team_idx": {+ "name": "ai_agent_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_agent_team_id_team_id_fk": {+ "name": "ai_agent_team_id_team_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_agent_user_id_user_id_fk": {+ "name": "ai_agent_user_id_user_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_agent_model_credential_id_integration_credential_id_fk": {+ "name": "ai_agent_model_credential_id_integration_credential_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "integration_credential",+ "columnsFrom": [+ "model_credential_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "ai_agent_owner_user_id_user_id_fk": {+ "name": "ai_agent_owner_user_id_user_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "ai_agent_user_id_unique": {+ "name": "ai_agent_user_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "ai_agent_kind_check": {+ "name": "ai_agent_kind_check",+ "value": "\"ai_agent\".\"kind\" IN ('external', 'internal')"+ },+ "ai_agent_runner_scope_check": {+ "name": "ai_agent_runner_scope_check",+ "value": "\"ai_agent\".\"runner_scope\" IN ('owner', 'team')"+ },+ "ai_agent_delegation_delay_check": {+ "name": "ai_agent_delegation_delay_check",+ "value": "\"ai_agent\".\"delegation_delay_sec\" >= 0 AND \"ai_agent\".\"delegation_delay_sec\" <= 86400"+ }+ },+ "isRLSEnabled": false+ },+ "public.app_secret": {+ "name": "app_secret",+ "schema": "",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.app_setting": {+ "name": "app_setting",+ "schema": "",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.chat_attachment": {+ "name": "chat_attachment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "uploaded_by_user_id": {+ "name": "uploaded_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_attachment_project_idx": {+ "name": "chat_attachment_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_attachment_project_id_project_id_fk": {+ "name": "chat_attachment_project_id_project_id_fk",+ "tableFrom": "chat_attachment",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_attachment_uploaded_by_user_id_user_id_fk": {+ "name": "chat_attachment_uploaded_by_user_id_user_id_fk",+ "tableFrom": "chat_attachment",+ "tableTo": "user",+ "columnsFrom": [+ "uploaded_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "chat_attachment_public_id_unique": {+ "name": "chat_attachment_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field": {+ "name": "custom_field",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_type_id": {+ "name": "issue_type_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_type": {+ "name": "field_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "member_scope": {+ "name": "member_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "show_in_body": {+ "name": "show_in_body",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "custom_field_project_id_project_id_fk": {+ "name": "custom_field_project_id_project_id_fk",+ "tableFrom": "custom_field",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "custom_field_issue_type_id_issue_type_id_fk": {+ "name": "custom_field_issue_type_id_issue_type_id_fk",+ "tableFrom": "custom_field",+ "tableTo": "issue_type",+ "columnsFrom": [+ "issue_type_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "custom_field_field_type_check": {+ "name": "custom_field_field_type_check",+ "value": "\"custom_field\".\"field_type\" IN ('text', 'markdown', 'url', 'number', 'boolean', 'date', 'datetime', 'datetime_range', 'select', 'multi_select', 'member')"+ },+ "custom_field_member_scope_check": {+ "name": "custom_field_member_scope_check",+ "value": "(\"custom_field\".\"field_type\" = 'member') = (\"custom_field\".\"member_scope\" IS NOT NULL) AND (\"custom_field\".\"member_scope\" IS NULL OR \"custom_field\".\"member_scope\" IN ('all', 'humans', 'agents'))"+ }+ },+ "isRLSEnabled": false+ },+ "public.custom_field_option": {+ "name": "custom_field_option",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {+ "custom_field_option_field_id_custom_field_id_fk": {+ "name": "custom_field_option_field_id_custom_field_id_fk",+ "tableFrom": "custom_field_option",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_option_field_id_value_unique": {+ "name": "custom_field_option_field_id_value_unique",+ "nullsNotDistinct": false,+ "columns": [+ "field_id",+ "value"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.cycle": {+ "name": "cycle",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "goal": {+ "name": "goal",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "end_date": {+ "name": "end_date",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "cycle_project_idx": {+ "name": "cycle_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "start_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "cycle_project_id_project_id_fk": {+ "name": "cycle_project_id_project_id_fk",+ "tableFrom": "cycle",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "cycle_dates_check": {+ "name": "cycle_dates_check",+ "value": "\"cycle\".\"end_date\" >= \"cycle\".\"start_date\""+ }+ },+ "isRLSEnabled": false+ },+ "public.document_asset": {+ "name": "document_asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "uploaded_by_user_id": {+ "name": "uploaded_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_asset_document_idx": {+ "name": "document_asset_document_idx",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "document_asset_document_id_project_document_id_fk": {+ "name": "document_asset_document_id_project_document_id_fk",+ "tableFrom": "document_asset",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "document_asset_uploaded_by_user_id_user_id_fk": {+ "name": "document_asset_uploaded_by_user_id_user_id_fk",+ "tableFrom": "document_asset",+ "tableTo": "user",+ "columnsFrom": [+ "uploaded_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "document_asset_public_id_unique": {+ "name": "document_asset_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_collaboration": {+ "name": "document_collaboration",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "epoch": {+ "name": "epoch",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "content_json": {+ "name": "content_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "document_collaboration_document_id_project_document_id_fk": {+ "name": "document_collaboration_document_id_project_document_id_fk",+ "tableFrom": "document_collaboration",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_comment": {+ "name": "document_comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_id": {+ "name": "author_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "quote": {+ "name": "quote",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "selection_from": {+ "name": "selection_from",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "selection_to": {+ "name": "selection_to",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "orphaned": {+ "name": "orphaned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_comment_document_idx": {+ "name": "document_comment_document_idx",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "document_comment_document_id_project_document_id_fk": {+ "name": "document_comment_document_id_project_document_id_fk",+ "tableFrom": "document_comment",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "document_comment_parent_id_document_comment_id_fk": {+ "name": "document_comment_parent_id_document_comment_id_fk",+ "tableFrom": "document_comment",+ "tableTo": "document_comment",+ "columnsFrom": [+ "parent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "document_comment_author_id_user_id_fk": {+ "name": "document_comment_author_id_user_id_fk",+ "tableFrom": "document_comment",+ "tableTo": "user",+ "columnsFrom": [+ "author_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_step": {+ "name": "document_step",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "step": {+ "name": "step",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "document_step_document_id_project_document_id_fk": {+ "name": "document_step_document_id_project_document_id_fk",+ "tableFrom": "document_step",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "document_step_document_id_version_pk": {+ "name": "document_step_document_id_version_pk",+ "columns": [+ "document_id",+ "version"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.git_managed_repository": {+ "name": "git_managed_repository",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "full_name": {+ "name": "full_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "web_url": {+ "name": "web_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "webhook_external_id": {+ "name": "webhook_external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'connected'"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "git_managed_repository_project_connection_idx": {+ "name": "git_managed_repository_project_connection_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "git_managed_repository_project_id_project_id_fk": {+ "name": "git_managed_repository_project_id_project_id_fk",+ "tableFrom": "git_managed_repository",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "git_managed_repository_connection_id_git_provider_connection_id_fk": {+ "name": "git_managed_repository_connection_id_git_provider_connection_id_fk",+ "tableFrom": "git_managed_repository",+ "tableTo": "git_provider_connection",+ "columnsFrom": [+ "connection_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "git_managed_repository_project_connection_external_unique": {+ "name": "git_managed_repository_project_connection_external_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "connection_id",+ "external_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.git_provider_connection": {+ "name": "git_provider_connection",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "base_url": {+ "name": "base_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "account_login": {+ "name": "account_login",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "git_provider_connection_team_idx": {+ "name": "git_provider_connection_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "git_provider_connection_team_id_team_id_fk": {+ "name": "git_provider_connection_team_id_team_id_fk",+ "tableFrom": "git_provider_connection",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.import_job": {+ "name": "import_job",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "phase": {+ "name": "phase",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'discover'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "cursor": {+ "name": "cursor",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "credential_ciphertext": {+ "name": "credential_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "credential_iv": {+ "name": "credential_iv",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "credential_auth_tag": {+ "name": "credential_auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "import_job_project_idx": {+ "name": "import_job_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "import_job_due_idx": {+ "name": "import_job_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"import_job\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "import_job_project_id_project_id_fk": {+ "name": "import_job_project_id_project_id_fk",+ "tableFrom": "import_job",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "import_job_created_by_user_id_user_id_fk": {+ "name": "import_job_created_by_user_id_user_id_fk",+ "tableFrom": "import_job",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "import_job_source_check": {+ "name": "import_job_source_check",+ "value": "\"import_job\".\"source\" IN ('plane', 'linear')"+ },+ "import_job_phase_check": {+ "name": "import_job_phase_check",+ "value": "\"import_job\".\"phase\" IN ('discover', 'create', 'link', 'rewrite', 'attachments', 'done')"+ },+ "import_job_status_check": {+ "name": "import_job_status_check",+ "value": "\"import_job\".\"status\" IN ('pending', 'running', 'paused', 'completed', 'failed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.import_record": {+ "name": "import_record",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "import_job_id": {+ "name": "import_job_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "source_entity_type": {+ "name": "source_entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_display_id": {+ "name": "source_display_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "local_entity_type": {+ "name": "local_entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "local_id": {+ "name": "local_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "import_record_job_source_uq": {+ "name": "import_record_job_source_uq",+ "columns": [+ {+ "expression": "import_job_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_entity_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "import_record_job_local_idx": {+ "name": "import_record_job_local_idx",+ "columns": [+ {+ "expression": "import_job_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "local_entity_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "local_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "import_record_job_display_idx": {+ "name": "import_record_job_display_idx",+ "columns": [+ {+ "expression": "import_job_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_entity_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_display_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "import_record_import_job_id_import_job_id_fk": {+ "name": "import_record_import_job_id_import_job_id_fk",+ "tableFrom": "import_record",+ "tableTo": "import_job",+ "columnsFrom": [+ "import_job_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "import_record_source_entity_type_check": {+ "name": "import_record_source_entity_type_check",+ "value": "\"import_record\".\"source_entity_type\" IN ('issue', 'comment', 'label', 'state', 'cycle', 'attachment')"+ },+ "import_record_local_entity_type_check": {+ "name": "import_record_local_entity_type_check",+ "value": "\"import_record\".\"local_entity_type\" IS NULL OR \"import_record\".\"local_entity_type\" IN ('issue', 'comment', 'label', 'state', 'cycle', 'attachment')"+ }+ },+ "isRLSEnabled": false+ },+ "public.initiative": {+ "name": "initiative",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'planned'"+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "target_date": {+ "name": "target_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "initiative_project_idx": {+ "name": "initiative_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "initiative_project_id_project_id_fk": {+ "name": "initiative_project_id_project_id_fk",+ "tableFrom": "initiative",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "initiative_owner_user_id_user_id_fk": {+ "name": "initiative_owner_user_id_user_id_fk",+ "tableFrom": "initiative",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "initiative_status_check": {+ "name": "initiative_status_check",+ "value": "\"initiative\".\"status\" IN ('proposed', 'planned', 'active', 'completed', 'canceled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.initiative_attachment": {+ "name": "initiative_attachment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "initiative_attachment_initiative_idx": {+ "name": "initiative_attachment_initiative_idx",+ "columns": [+ {+ "expression": "initiative_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "initiative_attachment_initiative_id_initiative_id_fk": {+ "name": "initiative_attachment_initiative_id_initiative_id_fk",+ "tableFrom": "initiative_attachment",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "initiative_attachment_public_id_unique": {+ "name": "initiative_attachment_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.initiative_label": {+ "name": "initiative_label",+ "schema": "",+ "columns": {+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "initiative_label_initiative_id_initiative_id_fk": {+ "name": "initiative_label_initiative_id_initiative_id_fk",+ "tableFrom": "initiative_label",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "initiative_label_label_id_label_id_fk": {+ "name": "initiative_label_label_id_label_id_fk",+ "tableFrom": "initiative_label",+ "tableTo": "label",+ "columnsFrom": [+ "label_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "initiative_label_initiative_id_label_id_pk": {+ "name": "initiative_label_initiative_id_label_id_pk",+ "columns": [+ "initiative_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration_credential": {+ "name": "integration_credential",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "integration_key": {+ "name": "integration_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_credential_team_idx": {+ "name": "integration_credential_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_credential_team_id_team_id_fk": {+ "name": "integration_credential_team_id_team_id_fk",+ "tableFrom": "integration_credential",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue": {+ "name": "issue",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "sequence_number": {+ "name": "sequence_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "type_id": {+ "name": "type_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cycle_id": {+ "name": "cycle_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_user_id": {+ "name": "assignee_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "delegate_user_id": {+ "name": "delegate_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "estimate_points": {+ "name": "estimate_points",+ "type": "numeric",+ "primaryKey": false,+ "notNull": false+ },+ "estimate_minutes": {+ "name": "estimate_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "share_token": {+ "name": "share_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "share_extended": {+ "name": "share_extended",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_project_active_idx": {+ "name": "issue_project_active_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"archived_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_project_title_idx": {+ "name": "issue_project_title_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lower(btrim(\"title\"))",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_parent_idx": {+ "name": "issue_parent_idx",+ "columns": [+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"parent_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_idx": {+ "name": "issue_cycle_idx",+ "columns": [+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"cycle_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_project_id_project_id_fk": {+ "name": "issue_project_id_project_id_fk",+ "tableFrom": "issue",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_type_id_issue_type_id_fk": {+ "name": "issue_type_id_issue_type_id_fk",+ "tableFrom": "issue",+ "tableTo": "issue_type",+ "columnsFrom": [+ "type_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_initiative_id_initiative_id_fk": {+ "name": "issue_initiative_id_initiative_id_fk",+ "tableFrom": "issue",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_cycle_id_cycle_id_fk": {+ "name": "issue_cycle_id_cycle_id_fk",+ "tableFrom": "issue",+ "tableTo": "cycle",+ "columnsFrom": [+ "cycle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_column_id_project_column_id_fk": {+ "name": "issue_column_id_project_column_id_fk",+ "tableFrom": "issue",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "issue_parent_id_issue_id_fk": {+ "name": "issue_parent_id_issue_id_fk",+ "tableFrom": "issue",+ "tableTo": "issue",+ "columnsFrom": [+ "parent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_assignee_user_id_user_id_fk": {+ "name": "issue_assignee_user_id_user_id_fk",+ "tableFrom": "issue",+ "tableTo": "user",+ "columnsFrom": [+ "assignee_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_delegate_user_id_user_id_fk": {+ "name": "issue_delegate_user_id_user_id_fk",+ "tableFrom": "issue",+ "tableTo": "user",+ "columnsFrom": [+ "delegate_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_share_token_unique": {+ "name": "issue_share_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "share_token"+ ]+ },+ "issue_project_id_sequence_number_unique": {+ "name": "issue_project_id_sequence_number_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "sequence_number"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "issue_estimate_points_check": {+ "name": "issue_estimate_points_check",+ "value": "\"issue\".\"estimate_points\" >= 0"+ },+ "issue_estimate_minutes_check": {+ "name": "issue_estimate_minutes_check",+ "value": "\"issue\".\"estimate_minutes\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_activity": {+ "name": "issue_activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reply_to_id": {+ "name": "reply_to_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_name": {+ "name": "actor_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "edited_at": {+ "name": "edited_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_activity_issue_idx": {+ "name": "issue_activity_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_activity_reply_idx": {+ "name": "issue_activity_reply_idx",+ "columns": [+ {+ "expression": "reply_to_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_activity_initiative_idx": {+ "name": "issue_activity_initiative_idx",+ "columns": [+ {+ "expression": "initiative_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_activity_issue_id_issue_id_fk": {+ "name": "issue_activity_issue_id_issue_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_initiative_id_initiative_id_fk": {+ "name": "issue_activity_initiative_id_initiative_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_reply_to_id_issue_activity_id_fk": {+ "name": "issue_activity_reply_to_id_issue_activity_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "reply_to_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_actor_user_id_user_id_fk": {+ "name": "issue_activity_actor_user_id_user_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "user",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_activity_kind_check": {+ "name": "issue_activity_kind_check",+ "value": "\"issue_activity\".\"kind\" IN ('comment', 'activity')"+ },+ "issue_activity_owner_check": {+ "name": "issue_activity_owner_check",+ "value": "(\"issue_activity\".\"issue_id\" IS NOT NULL) <> (\"issue_activity\".\"initiative_id\" IS NOT NULL)"+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_attachment": {+ "name": "issue_attachment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_attachment_issue_idx": {+ "name": "issue_attachment_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_attachment_issue_id_issue_id_fk": {+ "name": "issue_attachment_issue_id_issue_id_fk",+ "tableFrom": "issue_attachment",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_attachment_public_id_unique": {+ "name": "issue_attachment_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_checklist": {+ "name": "issue_checklist",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_checklist_issue_idx": {+ "name": "issue_checklist_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_checklist_issue_id_issue_id_fk": {+ "name": "issue_checklist_issue_id_issue_id_fk",+ "tableFrom": "issue_checklist",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_checklist_item": {+ "name": "issue_checklist_item",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "checklist_id": {+ "name": "checklist_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "done": {+ "name": "done",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_checklist_item_checklist_idx": {+ "name": "issue_checklist_item_checklist_idx",+ "columns": [+ {+ "expression": "checklist_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_checklist_item_checklist_id_issue_checklist_id_fk": {+ "name": "issue_checklist_item_checklist_id_issue_checklist_id_fk",+ "tableFrom": "issue_checklist_item",+ "tableTo": "issue_checklist",+ "columnsFrom": [+ "checklist_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_cycle": {+ "name": "issue_cycle",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "cycle_id": {+ "name": "cycle_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "entered_at": {+ "name": "entered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "left_at": {+ "name": "left_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "issue_cycle_issue_idx": {+ "name": "issue_cycle_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entered_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_cycle_idx": {+ "name": "issue_cycle_cycle_idx",+ "columns": [+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_open_idx": {+ "name": "issue_cycle_open_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_cycle\".\"left_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_cycle_issue_id_issue_id_fk": {+ "name": "issue_cycle_issue_id_issue_id_fk",+ "tableFrom": "issue_cycle",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_cycle_cycle_id_cycle_id_fk": {+ "name": "issue_cycle_cycle_id_cycle_id_fk",+ "tableFrom": "issue_cycle",+ "tableTo": "cycle",+ "columnsFrom": [+ "cycle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_development_check": {+ "name": "issue_development_check",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "development_link_id": {+ "name": "development_link_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "app_id": {+ "name": "app_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "head_sha": {+ "name": "head_sha",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_development_check_link_sha_idx": {+ "name": "issue_development_check_link_sha_idx",+ "columns": [+ {+ "expression": "development_link_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "head_sha",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_development_check_development_link_id_issue_development_link_id_fk": {+ "name": "issue_development_check_development_link_id_issue_development_link_id_fk",+ "tableFrom": "issue_development_check",+ "tableTo": "issue_development_link",+ "columnsFrom": [+ "development_link_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_development_check_development_link_id_app_id_name_unique": {+ "name": "issue_development_check_development_link_id_app_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "development_link_id",+ "app_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_development_link": {+ "name": "issue_development_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository": {+ "name": "repository",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pull_request'"+ },+ "external_key": {+ "name": "external_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "draft": {+ "name": "draft",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "source_branch": {+ "name": "source_branch",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "target_branch": {+ "name": "target_branch",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "head_sha": {+ "name": "head_sha",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "pipeline_status": {+ "name": "pipeline_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "pipeline_url": {+ "name": "pipeline_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_development_link_issue_idx": {+ "name": "issue_development_link_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_development_link_pr_idx": {+ "name": "issue_development_link_pr_idx",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "repository",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_development_link_sha_idx": {+ "name": "issue_development_link_sha_idx",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "repository",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "head_sha",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_development_link_issue_id_issue_id_fk": {+ "name": "issue_development_link_issue_id_issue_id_fk",+ "tableFrom": "issue_development_link",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_development_link_issue_id_provider_repository_external_key_unique": {+ "name": "issue_development_link_issue_id_provider_repository_external_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "issue_id",+ "provider",+ "repository",+ "external_key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_field_option": {+ "name": "issue_field_option",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "option_id": {+ "name": "option_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_field_option_issue_id_issue_id_fk": {+ "name": "issue_field_option_issue_id_issue_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_option_field_id_custom_field_id_fk": {+ "name": "issue_field_option_field_id_custom_field_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_option_option_id_custom_field_option_id_fk": {+ "name": "issue_field_option_option_id_custom_field_option_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "custom_field_option",+ "columnsFrom": [+ "option_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_field_option_issue_id_field_id_option_id_pk": {+ "name": "issue_field_option_issue_id_field_id_option_id_pk",+ "columns": [+ "issue_id",+ "field_id",+ "option_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_field_value": {+ "name": "issue_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "value_text": {+ "name": "value_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "value_number": {+ "name": "value_number",+ "type": "numeric",+ "primaryKey": false,+ "notNull": false+ },+ "value_bool": {+ "name": "value_bool",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "value_date": {+ "name": "value_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "value_datetime": {+ "name": "value_datetime",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "value_datetime_end": {+ "name": "value_datetime_end",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "value_user_id": {+ "name": "value_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_field_value_issue_id_issue_id_fk": {+ "name": "issue_field_value_issue_id_issue_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_value_field_id_custom_field_id_fk": {+ "name": "issue_field_value_field_id_custom_field_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_value_value_user_id_user_id_fk": {+ "name": "issue_field_value_value_user_id_user_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "user",+ "columnsFrom": [+ "value_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_field_value_issue_id_field_id_unique": {+ "name": "issue_field_value_issue_id_field_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "issue_id",+ "field_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_import": {+ "name": "issue_import",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'mapped'"+ },+ "mapping": {+ "name": "mapping",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "error_text": {+ "name": "error_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_import_project_idx": {+ "name": "issue_import_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_import_project_id_project_id_fk": {+ "name": "issue_import_project_id_project_id_fk",+ "tableFrom": "issue_import",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_import_attachment_id_chat_attachment_id_fk": {+ "name": "issue_import_attachment_id_chat_attachment_id_fk",+ "tableFrom": "issue_import",+ "tableTo": "chat_attachment",+ "columnsFrom": [+ "attachment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_import_public_id_unique": {+ "name": "issue_import_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_key_alias": {+ "name": "issue_key_alias",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "sequence_number": {+ "name": "sequence_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "issue_key_alias_issue_idx": {+ "name": "issue_key_alias_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_key_alias_project_id_project_id_fk": {+ "name": "issue_key_alias_project_id_project_id_fk",+ "tableFrom": "issue_key_alias",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_key_alias_issue_id_issue_id_fk": {+ "name": "issue_key_alias_issue_id_issue_id_fk",+ "tableFrom": "issue_key_alias",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_key_alias_project_id_sequence_number_pk": {+ "name": "issue_key_alias_project_id_sequence_number_pk",+ "columns": [+ "project_id",+ "sequence_number"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_label": {+ "name": "issue_label",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_label_issue_id_issue_id_fk": {+ "name": "issue_label_issue_id_issue_id_fk",+ "tableFrom": "issue_label",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_label_label_id_label_id_fk": {+ "name": "issue_label_label_id_label_id_fk",+ "tableFrom": "issue_label",+ "tableTo": "label",+ "columnsFrom": [+ "label_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_label_issue_id_label_id_pk": {+ "name": "issue_label_issue_id_label_id_pk",+ "columns": [+ "issue_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_link": {+ "name": "issue_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "source_issue_id": {+ "name": "source_issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "target_issue_id": {+ "name": "target_issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_link_pair_kind_idx": {+ "name": "issue_link_pair_kind_idx",+ "columns": [+ {+ "expression": "least(\"source_issue_id\", \"target_issue_id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "greatest(\"source_issue_id\", \"target_issue_id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_link_source_idx": {+ "name": "issue_link_source_idx",+ "columns": [+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_link_target_idx": {+ "name": "issue_link_target_idx",+ "columns": [+ {+ "expression": "target_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_link_source_issue_id_issue_id_fk": {+ "name": "issue_link_source_issue_id_issue_id_fk",+ "tableFrom": "issue_link",+ "tableTo": "issue",+ "columnsFrom": [+ "source_issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_link_target_issue_id_issue_id_fk": {+ "name": "issue_link_target_issue_id_issue_id_fk",+ "tableFrom": "issue_link",+ "tableTo": "issue",+ "columnsFrom": [+ "target_issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_link_kind_check": {+ "name": "issue_link_kind_check",+ "value": "\"issue_link\".\"kind\" IN ('blocks', 'relates', 'duplicates')"+ },+ "issue_link_self_check": {+ "name": "issue_link_self_check",+ "value": "\"issue_link\".\"source_issue_id\" <> \"issue_link\".\"target_issue_id\""+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_status": {+ "name": "issue_status",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "column_name": {+ "name": "column_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "state_type": {+ "name": "state_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "entered_at": {+ "name": "entered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "left_at": {+ "name": "left_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "issue_status_issue_idx": {+ "name": "issue_status_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entered_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_status_column_idx": {+ "name": "issue_status_column_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue_status\".\"column_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_status_open_idx": {+ "name": "issue_status_open_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_status\".\"left_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_status_issue_id_issue_id_fk": {+ "name": "issue_status_issue_id_issue_id_fk",+ "tableFrom": "issue_status",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_status_column_id_project_column_id_fk": {+ "name": "issue_status_column_id_project_column_id_fk",+ "tableFrom": "issue_status",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_template": {+ "name": "issue_template",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "title_template": {+ "name": "title_template",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "description_template": {+ "name": "description_template",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "type_id": {+ "name": "type_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_user_id": {+ "name": "assignee_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_template_project_id_project_id_fk": {+ "name": "issue_template_project_id_project_id_fk",+ "tableFrom": "issue_template",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_template_type_id_issue_type_id_fk": {+ "name": "issue_template_type_id_issue_type_id_fk",+ "tableFrom": "issue_template",+ "tableTo": "issue_type",+ "columnsFrom": [+ "type_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_template_column_id_project_column_id_fk": {+ "name": "issue_template_column_id_project_column_id_fk",+ "tableFrom": "issue_template",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_template_assignee_user_id_user_id_fk": {+ "name": "issue_template_assignee_user_id_user_id_fk",+ "tableFrom": "issue_template",+ "tableTo": "user",+ "columnsFrom": [+ "assignee_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_template_project_id_name_unique": {+ "name": "issue_template_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_template_label": {+ "name": "issue_template_label",+ "schema": "",+ "columns": {+ "template_id": {+ "name": "template_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_template_label_template_id_issue_template_id_fk": {+ "name": "issue_template_label_template_id_issue_template_id_fk",+ "tableFrom": "issue_template_label",+ "tableTo": "issue_template",+ "columnsFrom": [+ "template_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_template_label_label_id_label_id_fk": {+ "name": "issue_template_label_label_id_label_id_fk",+ "tableFrom": "issue_template_label",+ "tableTo": "label",+ "columnsFrom": [+ "label_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_template_label_template_id_label_id_pk": {+ "name": "issue_template_label_template_id_label_id_pk",+ "columns": [+ "template_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_type": {+ "name": "issue_type",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "is_default": {+ "name": "is_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_type_project_id_project_id_fk": {+ "name": "issue_type_project_id_project_id_fk",+ "tableFrom": "issue_type",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_type_project_id_name_unique": {+ "name": "issue_type_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_watcher": {+ "name": "issue_watcher",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "subscribed": {+ "name": "subscribed",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_watcher_issue_id_issue_id_fk": {+ "name": "issue_watcher_issue_id_issue_id_fk",+ "tableFrom": "issue_watcher",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_watcher_user_id_user_id_fk": {+ "name": "issue_watcher_user_id_user_id_fk",+ "tableFrom": "issue_watcher",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_watcher_issue_id_user_id_pk": {+ "name": "issue_watcher_issue_id_user_id_pk",+ "columns": [+ "issue_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_worklog": {+ "name": "issue_worklog",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "minutes": {+ "name": "minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "spent_on": {+ "name": "spent_on",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "note": {+ "name": "note",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_worklog_issue_idx": {+ "name": "issue_worklog_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "spent_on",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_worklog_issue_id_issue_id_fk": {+ "name": "issue_worklog_issue_id_issue_id_fk",+ "tableFrom": "issue_worklog",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_worklog_user_id_user_id_fk": {+ "name": "issue_worklog_user_id_user_id_fk",+ "tableFrom": "issue_worklog",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_worklog_minutes_check": {+ "name": "issue_worklog_minutes_check",+ "value": "\"issue_worklog\".\"minutes\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "group_id": {+ "name": "group_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "label_project_id_project_id_fk": {+ "name": "label_project_id_project_id_fk",+ "tableFrom": "label",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "label_group_id_label_group_id_fk": {+ "name": "label_group_id_label_group_id_fk",+ "tableFrom": "label",+ "tableTo": "label_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_project_id_name_unique": {+ "name": "label_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label_group": {+ "name": "label_group",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "label_group_project_id_project_id_fk": {+ "name": "label_group_project_id_project_id_fk",+ "tableFrom": "label_group",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_group_project_id_name_unique": {+ "name": "label_group_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.note_board": {+ "name": "note_board",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "canvas": {+ "name": "canvas",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "note_board_project_idx": {+ "name": "note_board_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "note_board_project_id_project_id_fk": {+ "name": "note_board_project_id_project_id_fk",+ "tableFrom": "note_board",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_owner_user_id_user_id_fk": {+ "name": "note_board_owner_user_id_user_id_fk",+ "tableFrom": "note_board",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_created_by_user_id_user_id_fk": {+ "name": "note_board_created_by_user_id_user_id_fk",+ "tableFrom": "note_board",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.note_board_member": {+ "name": "note_board_member",+ "schema": "",+ "columns": {+ "board_id": {+ "name": "board_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "note_board_member_user_idx": {+ "name": "note_board_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "note_board_member_board_id_note_board_id_fk": {+ "name": "note_board_member_board_id_note_board_id_fk",+ "tableFrom": "note_board_member",+ "tableTo": "note_board",+ "columnsFrom": [+ "board_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_member_user_id_user_id_fk": {+ "name": "note_board_member_user_id_user_id_fk",+ "tableFrom": "note_board_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "note_board_member_board_id_user_id_pk": {+ "name": "note_board_member_board_id_user_id_pk",+ "columns": [+ "board_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "source_activity_id": {+ "name": "source_activity_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_name": {+ "name": "actor_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "read_at": {+ "name": "read_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "snoozed_until": {+ "name": "snoozed_until",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_user_idx": {+ "name": "notification_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "notification_user_unread_idx": {+ "name": "notification_user_unread_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"notification\".\"read_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_project_id_project_id_fk": {+ "name": "notification_project_id_project_id_fk",+ "tableFrom": "notification",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_issue_id_issue_id_fk": {+ "name": "notification_issue_id_issue_id_fk",+ "tableFrom": "notification",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_source_activity_id_issue_activity_id_fk": {+ "name": "notification_source_activity_id_issue_activity_id_fk",+ "tableFrom": "notification",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "source_activity_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "notification_actor_user_id_user_id_fk": {+ "name": "notification_actor_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "notification_type_check": {+ "name": "notification_type_check",+ "value": "\"notification\".\"type\" IN ('assigned', 'mentioned', 'commented', 'state_changed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.notification_delivery": {+ "name": "notification_delivery",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "channel": {+ "name": "channel",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "recipient": {+ "name": "recipient",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_delivery_due_idx": {+ "name": "notification_delivery_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"notification_delivery\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_delivery_project_id_project_id_fk": {+ "name": "notification_delivery_project_id_project_id_fk",+ "tableFrom": "notification_delivery",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "notification_delivery_channel_check": {+ "name": "notification_delivery_channel_check",+ "value": "\"notification_delivery\".\"channel\" IN ('email', 'telegram')"+ }+ },+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "next_sequence": {+ "name": "next_sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "mcp_enabled": {+ "name": "mcp_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "initiatives_enabled": {+ "name": "initiatives_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "dashboards_enabled": {+ "name": "dashboards_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "documents_enabled": {+ "name": "documents_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "notes_enabled": {+ "name": "notes_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "cycles_enabled": {+ "name": "cycles_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "subtasks_enabled": {+ "name": "subtasks_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "checklists_enabled": {+ "name": "checklists_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "issue_stats_enabled": {+ "name": "issue_stats_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "points_estimate_enabled": {+ "name": "points_estimate_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "time_estimate_enabled": {+ "name": "time_estimate_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "time_logging_enabled": {+ "name": "time_logging_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_team_id_team_id_fk": {+ "name": "project_team_id_team_id_fk",+ "tableFrom": "project",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_team_key_uq": {+ "name": "project_team_key_uq",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_action": {+ "name": "project_action",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "condition": {+ "name": "condition",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "effect": {+ "name": "effect",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_action_project_idx": {+ "name": "project_action_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_action_project_id_project_id_fk": {+ "name": "project_action_project_id_project_id_fk",+ "tableFrom": "project_action",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_column": {+ "name": "project_column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state_type": {+ "name": "state_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unstarted'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "wip_limit": {+ "name": "wip_limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "wip_mode": {+ "name": "wip_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'soft'"+ },+ "auto_assign_user_id": {+ "name": "auto_assign_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_column_project_id_project_id_fk": {+ "name": "project_column_project_id_project_id_fk",+ "tableFrom": "project_column",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_column_auto_assign_user_id_user_id_fk": {+ "name": "project_column_auto_assign_user_id_user_id_fk",+ "tableFrom": "project_column",+ "tableTo": "user",+ "columnsFrom": [+ "auto_assign_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_column_project_id_position_unique": {+ "name": "project_column_project_id_position_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "position"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "project_column_state_type_check": {+ "name": "project_column_state_type_check",+ "value": "\"project_column\".\"state_type\" IN ('backlog', 'unstarted', 'started', 'completed', 'canceled')"+ },+ "project_column_wip_mode_check": {+ "name": "project_column_wip_mode_check",+ "value": "\"project_column\".\"wip_mode\" IN ('soft', 'hard')"+ },+ "project_column_wip_limit_check": {+ "name": "project_column_wip_limit_check",+ "value": "\"project_column\".\"wip_limit\" IS NULL OR \"project_column\".\"wip_limit\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_dashboard": {+ "name": "project_dashboard",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "layout": {+ "name": "layout",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_dashboard_project_idx": {+ "name": "project_dashboard_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_dashboard_project_id_project_id_fk": {+ "name": "project_dashboard_project_id_project_id_fk",+ "tableFrom": "project_dashboard",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_document": {+ "name": "project_document",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "content_json": {+ "name": "content_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "full_width": {+ "name": "full_width",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_private": {+ "name": "is_private",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_locked": {+ "name": "is_locked",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_ancestor_id": {+ "name": "archived_by_ancestor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_project_tree_idx": {+ "name": "project_document_project_tree_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_document_owner_idx": {+ "name": "project_document_owner_idx",+ "columns": [+ {+ "expression": "owner_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_document_project_archive_idx": {+ "name": "project_document_project_archive_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "archived_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_project_id_project_id_fk": {+ "name": "project_document_project_id_project_id_fk",+ "tableFrom": "project_document",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_parent_id_project_document_id_fk": {+ "name": "project_document_parent_id_project_document_id_fk",+ "tableFrom": "project_document",+ "tableTo": "project_document",+ "columnsFrom": [+ "parent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_archived_by_ancestor_id_project_document_id_fk": {+ "name": "project_document_archived_by_ancestor_id_project_document_id_fk",+ "tableFrom": "project_document",+ "tableTo": "project_document",+ "columnsFrom": [+ "archived_by_ancestor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_owner_user_id_user_id_fk": {+ "name": "project_document_owner_user_id_user_id_fk",+ "tableFrom": "project_document",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_created_by_user_id_user_id_fk": {+ "name": "project_document_created_by_user_id_user_id_fk",+ "tableFrom": "project_document",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_updated_by_user_id_user_id_fk": {+ "name": "project_document_updated_by_user_id_user_id_fk",+ "tableFrom": "project_document",+ "tableTo": "user",+ "columnsFrom": [+ "updated_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "project_document_version_check": {+ "name": "project_document_version_check",+ "value": "\"project_document\".\"version\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_document_initiative": {+ "name": "project_document_initiative",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_initiative_initiative_idx": {+ "name": "project_document_initiative_initiative_idx",+ "columns": [+ {+ "expression": "initiative_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_initiative_document_id_project_document_id_fk": {+ "name": "project_document_initiative_document_id_project_document_id_fk",+ "tableFrom": "project_document_initiative",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_initiative_initiative_id_initiative_id_fk": {+ "name": "project_document_initiative_initiative_id_initiative_id_fk",+ "tableFrom": "project_document_initiative",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_initiative_created_by_user_id_user_id_fk": {+ "name": "project_document_initiative_created_by_user_id_user_id_fk",+ "tableFrom": "project_document_initiative",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_document_initiative_document_id_initiative_id_pk": {+ "name": "project_document_initiative_document_id_initiative_id_pk",+ "columns": [+ "document_id",+ "initiative_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_document_issue": {+ "name": "project_document_issue",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_issue_issue_idx": {+ "name": "project_document_issue_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_issue_document_id_project_document_id_fk": {+ "name": "project_document_issue_document_id_project_document_id_fk",+ "tableFrom": "project_document_issue",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_issue_issue_id_issue_id_fk": {+ "name": "project_document_issue_issue_id_issue_id_fk",+ "tableFrom": "project_document_issue",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_issue_created_by_user_id_user_id_fk": {+ "name": "project_document_issue_created_by_user_id_user_id_fk",+ "tableFrom": "project_document_issue",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_document_issue_document_id_issue_id_pk": {+ "name": "project_document_issue_document_id_issue_id_pk",+ "columns": [+ "document_id",+ "issue_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_document_preference": {+ "name": "project_document_preference",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_favorite": {+ "name": "is_favorite",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_preference_user_idx": {+ "name": "project_document_preference_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_preference_document_id_project_document_id_fk": {+ "name": "project_document_preference_document_id_project_document_id_fk",+ "tableFrom": "project_document_preference",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_preference_user_id_user_id_fk": {+ "name": "project_document_preference_user_id_user_id_fk",+ "tableFrom": "project_document_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_document_preference_document_id_user_id_pk": {+ "name": "project_document_preference_document_id_user_id_pk",+ "columns": [+ "document_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_document_revision": {+ "name": "project_document_revision",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_json": {+ "name": "content_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "full_width": {+ "name": "full_width",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_private": {+ "name": "is_private",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_locked": {+ "name": "is_locked",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_revision_document_idx": {+ "name": "project_document_revision_document_idx",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_revision_document_id_project_document_id_fk": {+ "name": "project_document_revision_document_id_project_document_id_fk",+ "tableFrom": "project_document_revision",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_revision_owner_user_id_user_id_fk": {+ "name": "project_document_revision_owner_user_id_user_id_fk",+ "tableFrom": "project_document_revision",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_revision_created_by_user_id_user_id_fk": {+ "name": "project_document_revision_created_by_user_id_user_id_fk",+ "tableFrom": "project_document_revision",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_document_revision_document_version_unique": {+ "name": "project_document_revision_document_version_unique",+ "nullsNotDistinct": false,+ "columns": [+ "document_id",+ "version"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_member": {+ "name": "project_member",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'invite'"+ },+ "is_favorite": {+ "name": "is_favorite",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_hidden": {+ "name": "is_hidden",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_member_user_idx": {+ "name": "project_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_member_project_id_project_id_fk": {+ "name": "project_member_project_id_project_id_fk",+ "tableFrom": "project_member",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_member_user_id_user_id_fk": {+ "name": "project_member_user_id_user_id_fk",+ "tableFrom": "project_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_member_role_id_team_role_id_fk": {+ "name": "project_member_role_id_team_role_id_fk",+ "tableFrom": "project_member",+ "tableTo": "team_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_member_project_id_user_id_pk": {+ "name": "project_member_project_id_user_id_pk",+ "columns": [+ "project_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "project_member_role_check": {+ "name": "project_member_role_check",+ "value": "\"project_member\".\"role\" IN ('owner', 'member')"+ },+ "project_member_source_check": {+ "name": "project_member_source_check",+ "value": "\"project_member\".\"source\" IN ('invite', 'scim')"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_setting": {+ "name": "project_setting",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_setting_project_id_project_id_fk": {+ "name": "project_setting_project_id_project_id_fk",+ "tableFrom": "project_setting",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_setting_project_id_key_pk": {+ "name": "project_setting_project_id_key_pk",+ "columns": [+ "project_id",+ "key"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_view": {+ "name": "project_view",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "filters": {+ "name": "filters",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "display": {+ "name": "display",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "share_token": {+ "name": "share_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "share_extended": {+ "name": "share_extended",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_view_project_idx": {+ "name": "project_view_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_view_project_id_project_id_fk": {+ "name": "project_view_project_id_project_id_fk",+ "tableFrom": "project_view",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_view_share_token_unique": {+ "name": "project_view_share_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "share_token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_view_favorite": {+ "name": "project_view_favorite",+ "schema": "",+ "columns": {+ "view_id": {+ "name": "view_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_view_favorite_view_id_project_view_id_fk": {+ "name": "project_view_favorite_view_id_project_view_id_fk",+ "tableFrom": "project_view_favorite",+ "tableTo": "project_view",+ "columnsFrom": [+ "view_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_view_favorite_user_id_user_id_fk": {+ "name": "project_view_favorite_user_id_user_id_fk",+ "tableFrom": "project_view_favorite",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_view_favorite_view_id_user_id_pk": {+ "name": "project_view_favorite_view_id_user_id_pk",+ "columns": [+ "view_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.revision": {+ "name": "revision",+ "schema": "",+ "columns": {+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "rev": {+ "name": "rev",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {+ "revision_project_idx": {+ "name": "revision_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_enabled": {+ "name": "mcp_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "default_agent_ids": {+ "name": "default_agent_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_workspace_idx": {+ "name": "team_workspace_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_slug_unique": {+ "name": "team_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_invite": {+ "name": "team_invite",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "team_role": {+ "name": "team_role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "project_role": {+ "name": "project_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "invited_by_user_id": {+ "name": "invited_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accepted_by_user_id": {+ "name": "accepted_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "responded_at": {+ "name": "responded_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_invite_team_pending_uq": {+ "name": "team_invite_team_pending_uq",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"team_invite\".\"status\" = 'pending' AND \"team_invite\".\"project_id\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_invite_project_pending_uq": {+ "name": "team_invite_project_pending_uq",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"team_invite\".\"status\" = 'pending' AND \"team_invite\".\"project_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_invite_team_idx": {+ "name": "team_invite_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_invite_project_idx": {+ "name": "team_invite_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_invite_team_id_team_id_fk": {+ "name": "team_invite_team_id_team_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_invite_project_id_project_id_fk": {+ "name": "team_invite_project_id_project_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_invite_role_id_team_role_id_fk": {+ "name": "team_invite_role_id_team_role_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "team_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "team_invite_invited_by_user_id_user_id_fk": {+ "name": "team_invite_invited_by_user_id_user_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "user",+ "columnsFrom": [+ "invited_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "team_invite_accepted_by_user_id_user_id_fk": {+ "name": "team_invite_accepted_by_user_id_user_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "user",+ "columnsFrom": [+ "accepted_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_invite_token_unique": {+ "name": "team_invite_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "team_invite_team_role_check": {+ "name": "team_invite_team_role_check",+ "value": "\"team_invite\".\"team_role\" IN ('owner', 'manager', 'member')"+ },+ "team_invite_project_role_check": {+ "name": "team_invite_project_role_check",+ "value": "(\"team_invite\".\"project_id\" IS NULL AND \"team_invite\".\"project_role\" IS NULL)\n OR (\"team_invite\".\"project_id\" IS NOT NULL AND \"team_invite\".\"project_role\" IN ('owner', 'member'))"+ },+ "team_invite_status_check": {+ "name": "team_invite_status_check",+ "value": "\"team_invite\".\"status\" IN ('pending', 'accepted', 'rejected')"+ }+ },+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'invite'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_member_user_idx": {+ "name": "team_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "team_member_team_id_user_id_pk": {+ "name": "team_member_team_id_user_id_pk",+ "columns": [+ "team_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "team_member_role_check": {+ "name": "team_member_role_check",+ "value": "\"team_member\".\"role\" IN ('owner', 'manager', 'member', 'agent')"+ },+ "team_member_source_check": {+ "name": "team_member_source_check",+ "value": "\"team_member\".\"source\" IN ('invite', 'scim')"+ }+ },+ "isRLSEnabled": false+ },+ "public.team_notification_setting": {+ "name": "team_notification_setting",+ "schema": "",+ "columns": {+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "team_notification_setting_team_id_team_id_fk": {+ "name": "team_notification_setting_team_id_team_id_fk",+ "tableFrom": "team_notification_setting",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_role": {+ "name": "team_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_default": {+ "name": "is_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "permissions": {+ "name": "permissions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_role_default_uq": {+ "name": "team_role_default_uq",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"team_role\".\"is_default\"",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_role_team_idx": {+ "name": "team_role_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_role_team_id_team_id_fk": {+ "name": "team_role_team_id_team_id_fk",+ "tableFrom": "team_role",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_role_team_id_name_unique": {+ "name": "team_role_team_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "email_events": {+ "name": "email_events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "telegram_events": {+ "name": "telegram_events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_notification_preference_project_id_project_id_fk": {+ "name": "user_notification_preference_project_id_project_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_pref_user_project_unique": {+ "name": "user_notification_pref_user_project_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_preference": {+ "name": "user_preference",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'UTC'"+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "theme": {+ "name": "theme",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'system'"+ },+ "issue_open_mode": {+ "name": "issue_open_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'panel'"+ },+ "start_page": {+ "name": "start_page",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'work-items'"+ },+ "show_chat_by_default": {+ "name": "show_chat_by_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "issue_stats_open": {+ "name": "issue_stats_open",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "issue_stats_view": {+ "name": "issue_stats_view",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'compact'"+ },+ "issue_activity_view": {+ "name": "issue_activity_view",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'flat'"+ },+ "auto_watch": {+ "name": "auto_watch",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "hotkeys": {+ "name": "hotkeys",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "last_project_id": {+ "name": "last_project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "seen_version": {+ "name": "seen_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_preference_user_id_user_id_fk": {+ "name": "user_preference_user_id_user_id_fk",+ "tableFrom": "user_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_preference_last_project_id_project_id_fk": {+ "name": "user_preference_last_project_id_project_id_fk",+ "tableFrom": "user_preference",+ "tableTo": "project",+ "columnsFrom": [+ "last_project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "user_preference_theme_check": {+ "name": "user_preference_theme_check",+ "value": "\"user_preference\".\"theme\" IN ('light', 'dark', 'system')"+ },+ "user_preference_issue_open_mode_check": {+ "name": "user_preference_issue_open_mode_check",+ "value": "\"user_preference\".\"issue_open_mode\" IN ('panel', 'page')"+ },+ "user_preference_start_page_check": {+ "name": "user_preference_start_page_check",+ "value": "\"user_preference\".\"start_page\" IN ('inbox', 'dashboard', 'work-items', 'initiatives')"+ },+ "user_preference_issue_stats_view_check": {+ "name": "user_preference_issue_stats_view_check",+ "value": "\"user_preference\".\"issue_stats_view\" IN ('compact', 'timeline')"+ },+ "user_preference_issue_activity_view_check": {+ "name": "user_preference_issue_activity_view_check",+ "value": "\"user_preference\".\"issue_activity_view\" IN ('flat', 'grouped')"+ }+ },+ "isRLSEnabled": false+ },+ "public.user_telegram_account": {+ "name": "user_telegram_account",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "chat_id": {+ "name": "chat_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "link_code": {+ "name": "link_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "link_code_expires_at": {+ "name": "link_code_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "linked_at": {+ "name": "linked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_telegram_account_chat_id_unique": {+ "name": "user_telegram_account_chat_id_unique",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_telegram_account\".\"chat_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_telegram_account_link_code_unique": {+ "name": "user_telegram_account_link_code_unique",+ "columns": [+ {+ "expression": "link_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_telegram_account\".\"link_code\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_telegram_account_user_id_user_id_fk": {+ "name": "user_telegram_account_user_id_user_id_fk",+ "tableFrom": "user_telegram_account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.webhook": {+ "name": "webhook",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "events": {+ "name": "events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "consecutive_failures": {+ "name": "consecutive_failures",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "webhook_project_idx": {+ "name": "webhook_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "webhook_project_id_project_id_fk": {+ "name": "webhook_project_id_project_id_fk",+ "tableFrom": "webhook",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.webhook_delivery": {+ "name": "webhook_delivery",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "event_id": {+ "name": "event_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "response_status": {+ "name": "response_status",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "response_body": {+ "name": "response_body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "webhook_delivery_due_idx": {+ "name": "webhook_delivery_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"webhook_delivery\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "webhook_delivery_webhook_idx": {+ "name": "webhook_delivery_webhook_idx",+ "columns": [+ {+ "expression": "webhook_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "webhook_delivery_webhook_id_webhook_id_fk": {+ "name": "webhook_delivery_webhook_id_webhook_id_fk",+ "tableFrom": "webhook_delivery",+ "tableTo": "webhook",+ "columnsFrom": [+ "webhook_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_creation": {+ "name": "team_creation",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'owner'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "workspace_team_creation_check": {+ "name": "workspace_team_creation_check",+ "value": "\"workspace\".\"team_creation\" IN ('owner', 'managers', 'members')"+ }+ },+ "isRLSEnabled": false+ },+ "public.workspace_manager": {+ "name": "workspace_manager",+ "schema": "",+ "columns": {+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'admin'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_manager_owner_uq": {+ "name": "workspace_manager_owner_uq",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"workspace_manager\".\"role\" = 'owner'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_manager_user_idx": {+ "name": "workspace_manager_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_manager_workspace_id_workspace_id_fk": {+ "name": "workspace_manager_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_manager",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_manager_user_id_user_id_fk": {+ "name": "workspace_manager_user_id_user_id_fk",+ "tableFrom": "workspace_manager",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "workspace_manager_workspace_id_user_id_pk": {+ "name": "workspace_manager_workspace_id_user_id_pk",+ "columns": [+ "workspace_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "workspace_manager_role_check": {+ "name": "workspace_manager_role_check",+ "value": "\"workspace_manager\".\"role\" IN ('owner', 'admin')"+ }+ },+ "isRLSEnabled": false+ },+ "public.scim_group": {+ "name": "scim_group",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "scim_group_workspace_id_workspace_id_fk": {+ "name": "scim_group_workspace_id_workspace_id_fk",+ "tableFrom": "scim_group",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "scim_group_workspace_id_display_name_unique": {+ "name": "scim_group_workspace_id_display_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "display_name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.scim_group_mapping": {+ "name": "scim_group_mapping",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "group_id": {+ "name": "group_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "scim_group_mapping_project_idx": {+ "name": "scim_group_mapping_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_group_mapping_group_id_scim_group_id_fk": {+ "name": "scim_group_mapping_group_id_scim_group_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "scim_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_mapping_project_id_project_id_fk": {+ "name": "scim_group_mapping_project_id_project_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_mapping_role_id_team_role_id_fk": {+ "name": "scim_group_mapping_role_id_team_role_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "team_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "scim_group_mapping_group_id_project_id_unique": {+ "name": "scim_group_mapping_group_id_project_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "group_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "scim_group_mapping_role_check": {+ "name": "scim_group_mapping_role_check",+ "value": "\"scim_group_mapping\".\"role\" IN ('owner', 'member')"+ }+ },+ "isRLSEnabled": false+ },+ "public.scim_group_member": {+ "name": "scim_group_member",+ "schema": "",+ "columns": {+ "group_id": {+ "name": "group_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "scim_group_member_user_idx": {+ "name": "scim_group_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_group_member_group_id_scim_group_id_fk": {+ "name": "scim_group_member_group_id_scim_group_id_fk",+ "tableFrom": "scim_group_member",+ "tableTo": "scim_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_member_user_id_user_id_fk": {+ "name": "scim_group_member_user_id_user_id_fk",+ "tableFrom": "scim_group_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "scim_group_member_group_id_user_id_pk": {+ "name": "scim_group_member_group_id_user_id_pk",+ "columns": [+ "group_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.scim_user": {+ "name": "scim_user",+ "schema": "",+ "columns": {+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active": {+ "name": "active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "scim_user_user_idx": {+ "name": "scim_user_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_user_workspace_id_workspace_id_fk": {+ "name": "scim_user_workspace_id_workspace_id_fk",+ "tableFrom": "scim_user",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_user_user_id_user_id_fk": {+ "name": "scim_user_user_id_user_id_fk",+ "tableFrom": "scim_user",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "scim_user_workspace_id_user_id_pk": {+ "name": "scim_user_workspace_id_user_id_pk",+ "columns": [+ "workspace_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex 97034006..0e384d91 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -1002,6 +1002,13 @@"when": 1791308757273,"tag": "0142_issue_key_alias","breakpoints": true+ },+ {+ "idx": 143,+ "version": "7",+ "when": 1791374220064,+ "tag": "0143_import_job_linear_source",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/app.ts b/packages/db/src/schema/app.tsindex 72d7c79c..7573cf0d 100644--- a/packages/db/src/schema/app.ts+++ b/packages/db/src/schema/app.ts@@ -2229,8 +2229,8 @@ export const webhookDelivery = pgTable(// worker claims due rows the same way as webhook_delivery, and cursor is the// job's own per-phase resumability checkpoint, not the source API's pagination// cursor. The credential columns are cleared once the job reaches a terminal-// status; only 'plane' is supported as a source today.-export type ImportSource = 'plane';+// status. One source adapter per value (apps/worker/src/import-sources.ts).+export type ImportSource = 'plane' | 'linear';export const importJob = pgTable('import_job',@@ -2257,7 +2257,7 @@ export const importJob = pgTable(updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),},(t) => [- check('import_job_source_check', sql`${t.source} IN ('plane')`),+ check('import_job_source_check', sql`${t.source} IN ('plane', 'linear')`),check('import_job_phase_check',sql`${t.phase} IN ('discover', 'create', 'link', 'rewrite', 'attachments', 'done')`,diff --git a/packages/net/src/__tests__/bounded-fetch.test.ts b/packages/net/src/__tests__/bounded-fetch.test.tsindex c09bb370..b3ad3438 100644--- a/packages/net/src/__tests__/bounded-fetch.test.ts+++ b/packages/net/src/__tests__/bounded-fetch.test.ts@@ -1,6 +1,11 @@import { afterEach, describe, expect, it } from 'bun:test';import { createServer, type RequestListener } from 'node:http';-import { assertPublicHttpUrl, pinnedFetch, UrlNotAllowedError } from '../index';+import {+ assertPublicHttpUrl,+ pinnedFetch,+ ResponseTooLargeError,+ UrlNotAllowedError,+} from '../index';describe('public-only URL policy', () => {const environment = process.env.NODE_ENV;@@ -88,6 +93,9 @@ describe('bounded pinned fetch', () => {async (url) => {expect(await (await pinnedFetch(url, { maxBytes: 5 })).text()).toBe('12345');await expect(pinnedFetch(url, { maxBytes: 4 })).rejects.toThrow('byte limit');+ await expect(pinnedFetch(url, { maxBytes: 4 })).rejects.toBeInstanceOf(+ ResponseTooLargeError,+ );},);});diff --git a/packages/net/src/index.ts b/packages/net/src/index.tsindex 6b808715..6157cc8c 100644--- a/packages/net/src/index.ts+++ b/packages/net/src/index.ts@@ -14,6 +14,9 @@ import { request as httpsRequest } from 'node:https';export class UrlNotAllowedError extends Error {}+// A response body larger than the caller's maxBytes.+export class ResponseTooLargeError extends Error {}+// A hostname that is inherently local (not an IP literal).function isLocalHostname(host: string): boolean {return host === 'localhost' || host.endsWith('.local');@@ -261,7 +264,7 @@ export async function pinnedFetch(raw: string, init: PinnedRequestInit = {}): Prreq.destroy();return;}- const error = new Error('response exceeds the byte limit');+ const error = new ResponseTooLargeError('response exceeds the byte limit');res.destroy(error);req.destroy(error);return;